C++ TinyXML库读写XML
该库的下载地址:https://nchc.dl.sourceforge.net/project/tinyxml/tinyxml/2.6.2/tinyxml_2_6_2.zip
解压后,将解压目录下的tinystr.cpp,tinyxml.cpp,tinyxmlerror.cpp,tinyxmlparser.cpp,tinystr.h,tinyxml.h拷贝到自己的工程目录下。在头文件中引用#include "tinystr.h"和#include "tinyxml.h"
生成XML文件
#include <iostream>
#include<Windows.h>
#include "tinystr.h"
#include "tinyxml.h"
using namespace std;
int main()
{
TiXmlDocument doc;
//添加XML声明
doc.LinkEndChild(new TiXmlDeclaration("1.0", "GBK", ""));
//添加根元素
TiXmlElement* root = new TiXmlElement("root");
doc.LinkEndChild(root);
//根元素下添加子元素1
TiXmlElement* child1 = new TiXmlElement("item");
root->LinkEndChild(child1);
child1->LinkEndChild(new TiXmlText("第一项"));//设置文本
child1->SetAttribute("id", "1");//设置属性
//根元素下添加子元素2
TiXmlElement* child2 = new TiXmlElement("item");
root->LinkEndChild(child2);
child2->LinkEndChild(new TiXmlText("第二项"));
child2->SetAttribute("id", "2");
//在子元素2下添加子元素
TiXmlElement* subchild1 = new TiXmlElement("sub");
child2->LinkEndChild(subchild1);
subchild1->SetAttribute("name", "张三");
//保存xml文件
doc.SaveFile("wo.xml");
getchar();
}
生成的xml文件:
<?xml version="1.0" encoding="GBK" ?>
<root>
<item id="1">第一项</item>
<item id="2">第二项
<sub name="张三" />
</item>
</root>
读取XML文件
#include <iostream>
#include<Windows.h>
#include "tinystr.h"
#include "tinyxml.h"
using namespace std;
int main()
{
TiXmlDocument doc;
if (!doc.LoadFile("wo.xml"))
{
cout << "加载文件失败!" << endl;
return 1;
}
//根节点
TiXmlElement* root = doc.RootElement();
if (root == nullptr)
{
cout << "无根节点" << endl;
return 1;
}
//获取子节点信息
TiXmlElement* node1 = root->FirstChildElement("item");
const char* nodetext = node1->GetText();
const char* nodeid = node1->Attribute("id");
cout << "节点文本:" << nodetext << endl;
cout << "节点ID:" << nodeid << endl;
//遍历根节点下的子元素
for (TiXmlElement* sub = root->FirstChildElement(); sub != nullptr; sub = sub->NextSiblingElement())
{
cout << sub->Attribute("id") << endl;
}
doc.Clear();
getchar();
}