asp.net XMLDocument获取第一个节点与删除root节点方法

作者:袖梨 2022-06-25

xml技术来存储数据和文档是一件很容易的事情,.net framework 在它的命名空间system.xml 就提供了一种可以很方便的操作xml的类xmldocument,它使用起来非常容易,xmldocument 其实就是一个简单的树,下面我们就来看看关于 xmldocument获取第一个节点与删除root节点方法

#include "stdafx.h"

using namespace system;
using namespace system::xml;


void navigate(xmlnode ^node, int depth)
{
if (node == nullptr)
return;

console::writeline(depth);
console::writeline(node->nodetype.tostring());
console::writeline(node->name);
console::writeline(node->value);

if (node->attributes != nullptr)
{
for (int i = 0; i attributes->count; i++)
{
console::writeline(depth+1);
console::writeline(node->attributes[i]->name);
console::writeline(node->attributes[i]->value);
}
}
navigate(node->firstchild, depth+1);
navigate(node->nextsibling, depth);
}


void main()
{
xmldocument ^doc = gcnew xmldocument();
try
{
xmlreader ^reader = xmlreader::create("..monsters.xml");
doc->load(reader);
reader->close();
xmlnode ^node = doc->firstchild;


navigate(node, 0);
}
catch (exception ^e)
{
console::writeline("error occurred: {0}", e->message);
}
}

删除root节点

#include "stdafx.h"

using namespace system;
using namespace system::xml;
using namespace system::xml::xpath;

void navigate(xpathnavigator ^nav, int depth)
{
console::writeline(depth);
console::writeline(nav->nodetype.tostring());
console::writeline(nav->name);
console::writeline(nav->value);

if (nav->hasattributes)
{
nav->movetofirstattribute();
do {
console::writeline(nav->name);
console::writeline(nav->value);
}
while(nav->movetonextattribute());
nav->movetoparent();
}


if (nav->movetofirstchild())
{
navigate(nav, depth+1);
nav->movetoparent();
}
if (nav->movetonext())
navigate(nav, depth);
}

void main()
{
xmldocument ^doc = gcnew xmldocument();
try
{
doc->load("..monsters.xml");
xpathnavigator ^nav = doc->createnavigator();
nav->movetoroot();
navigate(nav, 0);
}
catch (exception ^e)
{
console::writeline("error occurred: {0}", e->message);
}
}

相关文章

精彩推荐