pugixml.cpp遍历子节点
时间: 2023-07-12 22:32:23 浏览: 121
要遍历pugixml中的子节点,可以使用pugi::xml_node的child和next_sibling方法。child方法返回第一个子节点,next_sibling方法返回下一个同级节点。
以下是示例代码:
```c++
#include "pugixml.hpp"
#include <iostream>
using namespace std;
using namespace pugi;
int main()
{
xml_document doc;
if (!doc.load_file("example.xml"))
{
cout << "Error loading file." << endl;
return 1;
}
xml_node root = doc.child("root");
// 遍历所有子节点
for (xml_node node = root.first_child(); node; node = node.next_sibling())
{
cout << "Node name: " << node.name() << endl;
// 遍历子节点的所有属性
for (xml_attribute attr = node.first_attribute(); attr; attr = attr.next_attribute())
{
cout << "Attribute name: " << attr.name() << ", value: " << attr.value() << endl;
}
// 遍历子节点的所有子节点
for (xml_node child = node.first_child(); child; child = child.next_sibling())
{
cout << "Child node name: " << child.name() << ", value: " << child.child_value() << endl;
}
}
return 0;
}
```
这个例子中,我们首先加载了一个XML文件,然后获取了根节点。接着,我们使用first_child方法获取第一个子节点,并使用next_sibling方法遍历了所有同级节点。在每个节点上,我们使用first_attribute方法遍历了所有属性,并使用first_child方法遍历了所有子节点。