I want to configure a device using an XML file and was thinking that I can make the individual pugi::xml_node
s first with the values I need and later on make them children of a document or some parent node. However, I seem to be doing something wrong.
Example that works:
#include "pugixml.hpp"
int main(){
pugi::xml_document xml;
pugi::xml_node configRecord = xml.append_child("configrecord");
pugi::xml_node configGroup = configRecord.append_child("configgroup");
configGroup.append_attribute("name") = "ftp server";
}
This works because I first create the parent document and then start branching by adding children. I was thinking that I can first make the node objects, store them into an array and parse that array to add them to the document. But this doesn't work.
#include "pugixml.hpp"
int main(){
pugi::xml_node myNode;
myNode.set_name("value");
myNode.append_child(pugi::node_pcdata).set_value("enable");
pugi::xml_document docu;
docu.set_name("document");
docu.child(myNode); // <- error here, cannot add child to document
}
Can I somehow use the strategy I was planning to or am I constrained to only adding children to an existing parent?
pugixml documentation states that pugi::xml_node
is a non-owning pointer to actual node data stored in a pugi::xml_document
object:
xml_node
is the handle to document node; it can point to any node in the document, including the document node itself. There is a common interface for nodes of all types; the actual node type can be queried via thexml_node::type()
method. Note thatxml_node
is only a handle to the actual node, not the node itself
Nodes and attributes do not exist without a document tree, so you can’t create them without adding them to some document.
It seems to me that your code doesn't throw errors when you try to manipulate myNode
because default-constructed "null" nodes silently consume operations on them to make chaining easier:
all operations are defined on empty nodes; generally the operations don’t do anything and return empty nodes/attributes or empty strings as their result [...] This is useful for chaining calls