C++调用tinyxml2遍历xml所有节点且使用map输出的简单例子
本例子一共只需要3个文件
大家好,本文目的是实现C++调用tinyxml2遍历xml所有节点且使用map输出的简单例子;
第一个文件是自己编写的main.cpp文件;
第二个文件是自己编写的ElectronicProduct.xml文件
第三个文件和第四个文件分别是tinyxml2.h和tinyxml2.cpp这两个文件为需要调用的包
获取所有代码请到github下载地址:
获取所有代码
方法一:下载链接: link 也可以复制链接浏览器打开(https://github.com/SDJMCGSJZY/tinyxml2Example.git) 注意本例子用到的是文件夹tinyxml2example02中的文件
方法二:main.cc复制本篇博客中的内容
ElectronicProduct.xml复制本篇博客中的内容
tinyxml2.h和tinyxml2.cpp可以在link即博客(https://blog.csdn.net/qq_36511600/article/details/104803508)中进行复制下载
哔哩哔哩有详细的视频讲解地址:
后续会将链接发出来
main.cpp
自己需要写的main.cpp文件
#include <iostream>
#include"tinyxml2.h"
#include <map>
using namespace std;
using namespace tinyxml2;
//核心代码,递归实现读取xml的节点
void GetElementValue(XMLElement *element , std::map<std::string, std::string> &itemID_value_map)
{
for (XMLElement* currenteleElement = element->FirstChildElement(); currenteleElement; currenteleElement = currenteleElement->NextSiblingElement())
{
XMLElement* tmpele = currenteleElement;
if (currenteleElement->GetText() != NULL)
{
cout << "ItemID = " << currenteleElement->Attribute("ItemID") << "---Value = " << currenteleElement->GetText() << endl;
itemID_value_map[currenteleElement->Attribute("ItemID")] = currenteleElement->GetText();
}
//判断该节点是否为空,如果不为空则继续递归
if (!tmpele->NoChildren())
GetElementValue(tmpele,itemID_value_map);
}
}
//递归读取xml文件中的节点,并且保存到map中
std::map<std::string,std::string> CycleReadAllNode(std::string xmlPath)
{
static std::map<std::string, std::string> itemID_value_map;
itemID_value_map.clear();
tinyxml2::XMLDocument xml;
if (xml.LoadFile(xmlPath.c_str()) != XML_SUCCESS)
{
return itemID_value_map; //return empty map
}
tinyxml2::XMLElement* rootNode = xml.RootElement();
if (rootNode == NULL) {
return itemID_value_map; //return empty map
}
GetElementValue(rootNode, itemID_value_map);
return itemID_value_map;
}
int main()
{
std::map<std::string, std::string> maps = CycleReadAllNode("ElectronicProduct.xml");
//遍历map
cout << "-----------------------begin 循环遍历节点------------------------" << endl;
std::map<std::string, std::string>::iterator iter;
for (iter = maps.begin(); iter != maps.end(); iter++)
{
std::cout << "itemId = " << (iter->first).c_str() << "-------value = " << (iter->second).c_str() << std::endl;
}
cout << "-----------------------end 循环遍历节点------------------------" << endl;
return 0;
}
ElectronicProduct.xml
自己需要写的ElectronicProduct.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ElectronicProduct>
<computer ItemID = "DELL">8000yuan</computer>
<computer ItemID = "MAC PRO">16000yuan</computer>
<pad ItemID = "ipadmin3">1600yuan</pad>
</ElectronicProduct>
其他
谢谢您的阅读;如果本文有任何不妥的地方,请留言;