Create an XML tree from scratch - pugixml C ++

First, I would like to say that I am using an XML parser written by Frank Vanden Bergen and recently trying to switch to Pugixml. I find the transition bit complicated. Hope to get help here.

Question: How can I build a tree from scratch for a little xml below using pugixml APIs? I tried to learn the examples on the pugixml homepage, but most of them are hardcoded with root node values. I mean

if (!doc.load("<node id='123'>text</node><!-- comment -->", pugi::parse_default | pugi::parse_comments)) return -1; 

hardcoded. I also tried reading about the xml_document and xml_node documentation, but couldn't figure out where to start if I needed to build a tree from scratch.

 #include "pugixml.hpp" #include <string.h> #include <iostream> int main() { pugi::xml_document doc; if (!doc.load("<node id='123'>text</node><!-- comment -->", pugi::parse_default | pugi::parse_comments)) return -1; //[code_modify_base_node pugi::xml_node node = doc.child("node"); // change node name std::cout << node.set_name("notnode"); std::cout << ", new node name: " << node.name() << std::endl; // change comment text std::cout << doc.last_child().set_value("useless comment"); std::cout << ", new comment text: " << doc.last_child().value() << std::endl; // we can't change value of the element or name of the comment std::cout << node.set_value("1") << ", " << doc.last_child().set_name("2") << std::endl; //] //[code_modify_base_attr pugi::xml_attribute attr = node.attribute("id"); // change attribute name/value std::cout << attr.set_name("key") << ", " << attr.set_value("345"); std::cout << ", new attribute: " << attr.name() << "=" << attr.value() << std::endl; // we can use numbers or booleans attr.set_value(1.234); std::cout << "new attribute value: " << attr.value() << std::endl; // we can also use assignment operators for more concise code attr = true; std::cout << "final attribute value: " << attr.value() << std::endl; //] } // vim:et 

XML:

 <?xml version="1.0" encoding="UTF-8"?> <d:testrequest xmlns:d="DAV:" xmlns:o="urn:example.com:testdrive"> <d:basicsearch> <d:select> <d:prop> <o:versionnumber/> <d:creationdate /> </d:prop> </d:select> <d:from> <d:scope> <d:href>/</d:href> <d:depth>infinity</d:depth> </d:scope> </d:from> <d:where> <d:like> <d:prop> <o:name /> </d:prop> <d:literal>%img%</d:literal> </d:like> </d:where> </d:basicsearch> </d:testrequest> 

I could see most of the examples published on how to read / parse xml, but I could not find how to create it from scratch.

+8
c ++ xml pugixml
source share
2 answers

The pugixml homepage provides sample code for creating an XML tree from scratch.

Summary: use the default constructor for pugi::xml_document doc , then append_child for the root of the node. Usually, node is first inserted. The return value of the insert call then serves as a handle to populate the XML node.

XML tree building

+8
source share
+9
source share

All Articles