我可以将对象的子对象设置为在 PugiXML 中单独定义的对象吗?

Can I set the child of an object to be an object defined separetely in PugiXML?

我想使用 XML 文件配置一个设备,我想我可以先用我需要的值创建单个 pugi::xml_node,然后再将它们设置为文档的子项或一些父节点。不过,我好像做错了什么。

有效示例:

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

之所以可行,是因为我首先创建父文档,然后通过添加子文档开始分支。我在想我可以先制作节点对象,将它们存储到一个数组中并解析该数组以将它们添加到文档中。但这是行不通的。

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

我能否以某种方式使用我计划使用的策略,或者我是否只能将子项添加到现有的父项中?

pugixml documentation 声明 pugi::xml_node 是指向存储在 pugi::xml_document 对象中的实际节点数据的非拥有指针:

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 the xml_node::type() method. Note that xml_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.

在我看来,当您尝试操作 myNode 时,您的代码不会抛出错误,因为默认构造的“空”节点会默默地消耗对它们的操作以简化链接:

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