微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。