一, 用 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;
- }
来源: http://www.bubuko.com/infodetail-3213489.html