TinyXML-2 是一个简单、小巧的 C++ XML 解析库,它是 TinyXML 的一个改进版本,专注于易用性和性能。TinyXML-2 用于读取、修改和创建 XML 文档。它不依赖于外部库,并且可以很容易地集成到项目中。
tinyXML-2 的主要特点包括:
下载地址:https://github.com/leethomason/tinyxml2/tree/10.0.0

解压文件后,直接引用以下两个文件即可。

解析XML字符串。
#include
#include "tinyxml2.h"
using namespace std;
using namespace tinyxml2;
int main()
{
static const char* xml =
""
""
""
" "
" "
" 2 "
" "
"";
XMLDocument doc;
doc.Parse(xml);
int v0 = 0;
int v1 = 0;
XMLElement* attributeApproachElement = doc.FirstChildElement()->FirstChildElement("attributeApproach");
attributeApproachElement->QueryIntAttribute("v", &v0);
XMLElement* textApproachElement = doc.FirstChildElement()->FirstChildElement("textApproach");
textApproachElement->FirstChildElement("v")->QueryIntText(&v1);
printf("Both values are the same: %d and %d\n", v0, v1);
return doc.ErrorID();
}
使用以下代码,可以直接加载XML文件。
XMLDocument doc;
doc.LoadFile( "resources/dream.xml" );
写入XML文件。
#include
#include "tinyxml2.h"
using namespace std;
using namespace tinyxml2;
int main()
{
XMLDocument* doc = new XMLDocument();
XMLNode* declaration = doc->InsertFirstChild(doc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\""));
XMLNode* element = doc->InsertEndChild(doc->NewElement("element"));
XMLElement* sub[3] = { doc->NewElement("sub"), doc->NewElement("sub"), doc->NewElement("sub") };
for (int i = 0; i < 3; ++i)
{
sub[i]->SetAttribute("attrib", i);
}
element->InsertEndChild(sub[2]);
XMLNode* comment = element->InsertFirstChild(doc->NewComment("comment"));
element->InsertAfterChild(comment, sub[0]);
element->InsertAfterChild(sub[0], sub[1]);
sub[2]->InsertFirstChild(doc->NewText("Text!"));
XMLElement* sub4 = doc->NewElement("textApproach");
element->InsertAfterChild(sub[2], sub4);
XMLElement* sub5 = doc->NewElement("v");
sub4->InsertFirstChild(sub5);
sub5->InsertFirstChild(doc->NewText("2"));
doc->Print();
doc->SaveFile("./pretty.xml");
return 0;
}
运行结果:
