一、用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; }