要寫入xml文件的內容
<?xml version="1.0" encoding="UTF-8"?>
<!--this is a comment-->
<html>
<head>this is a heading!</head>
<body>
<p>this is a paragraph!</p>
<h1>this is first heading!</h1>
</body>
</html>
代碼實現
#include <iostream>
#include "tinyxml2.h"
using namespace std;
using namespace tinyxml2;
/**************************************
<?xml version="1.0" encoding="UTF-8"?>
<!--this is a comment-->
<html>
<head>this is a heading!</head>
<body>
<p>this is a paragraph!</p>
<h1>this is first heading!</h1>
</body>
</html>
**************************************/
int main()
{
XMLDocument doc;
doc.LinkEndChild(doc.NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\""));
doc.LinkEndChild(doc.NewComment("this is a comment"));
auto htmlElement = doc.NewElement("html");
auto headElement = doc.NewElement("head");
headElement->SetText("this is a heading!");
auto bodyElement = doc.NewElement("body");
htmlElement->LinkEndChild(headElement);
htmlElement->LinkEndChild(bodyElement);
auto pElement = doc.NewElement("p");
pElement->SetText("this is a paragraph!");
auto h1Element = doc.NewElement("h1");
h1Element->SetText("this is first heading!");
bodyElement->LinkEndChild(pElement);
bodyElement->LinkEndChild(h1Element);
doc.LinkEndChild(htmlElement);
XMLPrinter printer;
doc.Print(&printer);
cout<< printer.CStr() << endl;
doc.SaveFile("myXML.xml");
return 0;
}
代碼解析
XMLDocument 代表XML文件; XMLDeclaration 代表XML文檔聲明;XMLComment 代表XML註釋; XMLElement 代表一個XML元素。。。
通過 XMLDocument的NewXXXX可以new出以上各種對象,然後每個元素分別調用LinkEndChild將屬於自己的子元素掛載到
自己的元素對間。
XMLPrinter用於打印XML文檔;
XMLDocument的SaveFile()將保存文件到指定的磁盤位置中。
運行結果