網上下載tinyxml2.h和tinyxml2.cpp,Windows和linux都可以用。
VC++編譯後得到tinyxml2.lib和tinyxml2.dll。
新建項目,包含tinyxml2.h文件
#include <stdio.h>
#include <tinyxml2.h>
#pragma comment(lib,"tinyxml2.lib")
using namespace tinyxml2;
void createXML()
{
XMLDocument doc;
char* declaration = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
doc.Parse(declaration);
XMLComment* comment = doc.NewComment("this is a xml test file");
doc.InsertEndChild(comment);
XMLElement* root = doc.NewElement("Root");
doc.InsertEndChild(root);
XMLElement* user = doc.NewElement("User");
user->SetAttribute("Name", "fengbingchun");
root->InsertEndChild(user);
XMLElement* blog = doc.NewElement("Blog");
XMLText* text1 = doc.NewText("CSDN");
blog->InsertEndChild(text1);
user->InsertEndChild(blog);
doc.SaveFile("test1.xml");
}
void readXML()
{
XMLDocument doc;
doc.LoadFile("test2.xml");
XMLElement* root = doc.RootElement();
XMLElement* ip = root->FirstChildElement("ip");
printf("ip:%s\n",ip->GetText());
XMLElement* port = root->FirstChildElement("port");
printf("ip:%d\n", atoi(port->GetText()));
XMLElement* username = root->FirstChildElement("username");
printf("username:%s\n", username->GetText());
XMLElement* password = root->FirstChildElement("password");
printf("password:%s\n", password->GetText());
XMLElement* MonitorDir = root->FirstChildElement("MonitorDir");
printf("MonitorDir:%s\n", MonitorDir->GetText());
XMLElement* remotePath = root->FirstChildElement("remotePath");
printf("remotePath:%s\n", remotePath->GetText());
}
int main()
{
readXML();
getchar();
return 0;
}
創建的xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<!--this is a xml test file-->
<Root>
<User Name="fengbingchun">
<Blog>CSDN</Blog>
</User>
</Root>
讀取的 xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<ftp>
<ip>192.168.100.5</ip>
<port>21</port>
<username>rxm25</username>
<password>rxm25</password>
<MonitorDir>MonitorDir</MonitorDir>
<remotePath>rxm25Data</remotePath>
</ftp>
附Qt操作xml鏈接:https://www.cnblogs.com/warmlight/p/11389944.html