XML的读写操作(生成XML & 解析XML)

时间:2019-09-26
本文章向大家介绍XML的读写操作(生成XML & 解析XML),主要包括XML的读写操作(生成XML & 解析XML)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、用Poco库

Poco库是下载、编译和使用:www.cnblogs.com/htj10/p/11380144.html

1. 生成XML

#include <Poco/AutoPtr.h>
#include <Poco/DOM/Document.h> //for Poco::XML::Document
#include <Poco/DOM/Element.h>  //for Poco::XML::Element
#include <Poco/DOM/Text.h>       //for Poco::XML::Text
#include <Poco/DOM/ProcessingInstruction.h> //for Poco::XML::ProcessingInstruction
#include <Poco/DOM/Comment.h>  //for Poco::XML::Comment
#include <Poco/DOM/DOMWriter.h> //for Poco::XML::DOMWriter
#include <Poco/XML/XMLWriter.h> //for Poco::XML::XMLWriter
#include <sstream>

int main(int argc, char** argv)
{
    //Poco生成XML
    Poco::AutoPtr<Poco::XML::Document> pDoc = new Poco::XML::Document;
    Poco::AutoPtr<Poco::XML::ProcessingInstruction> pi = pDoc->createProcessingInstruction("xml","version='1.0' encoding='UTF-8'");
    Poco::AutoPtr<Poco::XML::Comment> pComment = pDoc->createComment("The information of some Universities.");
    Poco::AutoPtr<Poco::XML::Element> pRoot = pDoc->createElement("University_info");

    Poco::AutoPtr<Poco::XML::Element> pChild = pDoc->createElement("University");
    pChild->setAttribute("name", "Harvard");
    Poco::AutoPtr<Poco::XML::Element> pGrandchild1 = pDoc->createElement("school");
    pGrandchild1->setAttribute("name", "Secient");
    Poco::AutoPtr<Poco::XML::Element> pGrandchild2 = pDoc->createElement("school");
    pGrandchild2->setAttribute("name", "Mathematics");

    Poco::AutoPtr<Poco::XML::Element> pNumOfPeople = pDoc->createElement("people_counting");
    Poco::AutoPtr<Poco::XML::Text> pText = pDoc->createTextNode("123");
    pNumOfPeople->appendChild(pText);

    pDoc->appendChild(pi);
    pDoc->appendChild(pComment);
    pDoc->appendChild(pRoot);
    pRoot->appendChild(pChild);
    pChild->appendChild(pGrandchild1);
    pChild->appendChild(pGrandchild2);
    pGrandchild1->appendChild(pNumOfPeople);

    Poco::XML::DOMWriter writer;
    writer.setOptions(Poco::XML::XMLWriter::PRETTY_PRINT);// PRETTY_PRINT = 4
    writer.writeNode("./example.xml", pDoc);//直接写进文件
    //或者直接写进string
    std::stringstream sstr;
    writer.writeNode(sstr, pDoc);
    std::string s = sstr.str();

    return 0;
}

原文地址:https://www.cnblogs.com/htj10/p/11589357.html