tinyxml2遍历多级节点的属性和文本
·
XML中的内容如下
<?xml version="1.0" encoding="UTF-8"?>
<dds_data>
<!-- AIS主题数据 -->
<AIS topic="AIS">
<node type="string">SOG</node>
<node type="float">COG</node>
</AIS>
<!-- GPS主题数据 -->
<GPS topic="GPS">
<node>GGA</node>
<node>GSV</node>
</GPS>
</dds_data>
使用tinyxml2解析XML配置文件
#include <iostream>
#include "../../tinyxml2/tinyxml2.h"
using namespace std;
using namespace tinyxml2;
int main()
{
XMLDocument doc;
doc.LoadFile("./public.xml");
if(doc.ErrorID() != XML_SUCCESS){
cout << "Read xml error." << endl;
}
// 根节点
XMLElement* root = doc.RootElement();
// AIS子节点
XMLElement* ais_node = root->FirstChildElement("AIS");
// AIS子节点的属性
cout << ais_node->Attribute("topic") << endl;
// AIS子节点下的第一个元素
XMLElement* ais_child_node = ais_node->FirstChildElement("node");
while (ais_child_node != nullptr) {
if(ais_child_node->GetText() != nullptr){
// 元素的属性和文本
cout << ais_child_node->GetText() << " "
<< ais_child_node->Attribute("type") << endl;
}
ais_child_node = ais_child_node->NextSiblingElement();
}
XMLElement* gps_node = root->FirstChildElement("GPS");
cout << gps_node->Attribute("topic") << endl;
auto gps_child_node = gps_node->FirstChildElement("node");
while (gps_child_node != nullptr) {
if(gps_child_node->GetText() != nullptr){
cout << gps_child_node->GetText() << endl;
}
gps_child_node = gps_child_node->NextSiblingElement();
}
for(auto item = gps_node->FirstChildElement("node"); item != nullptr; item = item->NextSiblingElement()){
if(item->GetText() != nullptr){
cout << item->GetText() << endl;
}
}
return 0;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)