TinyXML-2 写 XML 文件

要写入xml文件的内容




  this is a heading!
  
    

this is a paragraph!

this is first heading!

代码实现

#include 
#include "tinyxml2.h"

using namespace std;
using namespace tinyxml2;

/**************************************



  this is a heading!
  
    

this is a paragraph!

this is first heading!

**************************************/ 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()将保存文件到指定的磁盘位置中。

 

运行结果

TinyXML-2 写 XML 文件_第1张图片

TinyXML-2 写 XML 文件_第2张图片

 

 

 

 

 

你可能感兴趣的:(TinyXML-2)