C++ pugiXML,在节点中的第一个 child 之前附加一个 child
C++ pugiXML, Append a child before the first child in a node
如何将新的 child 附加到节点并将其放在第一个 child 之前?即我想尝试附加一个新的 child 并将其按顺序推到顶部。
说,如果我有:
pugi::xml_node root;
pugi::xml_node level1 = root.append_child("Level1");
pugi::xml_node level2 = root.append_child("Level2");
pugi::xml_node level3 = root.append_child("Level3");
我能否以某种方式附加一个新节点 level4
并将其放在 XML 树中的 level1
节点之前?
您可以使用 root.insert_child_before("Level4", root.first_child())
.
它的评分者不寻常地为每个 child 设置了不同的标签名称。一种更常见的格式是让 children 都具有相同的名称并设置属性以将它们彼此区分开来。
一个如何做到这一点的例子:
int main()
{
pugi::xml_document doc;
pugi::xml_node root = doc.append_child("levels");
root.append_child("level").append_attribute("id").set_value("L01");
root.last_child().append_child("description").text().set("Some L01 stuff");
root.append_child("level").append_attribute("id").set_value("L02");
root.last_child().append_child("description").text().set("Some L02 stuff");
// now insert one before the first child
root.insert_child_before("level", root.first_child()).append_attribute("id").set_value("L00");
root.first_child().append_child("description").text().set("Some L00 stuff");
doc.print(std::cout);
}
输出:
<levels>
<level id="L00">
<description>Some L00 stuff</description>
</level>
<level id="L01">
<description>Some L01 stuff</description>
</level>
<level id="L02">
<description>Some L02 stuff</description>
</level>
</levels>
刚刚有人教我做 prepend_child
。仍然感谢 Galik 的建议。
如何将新的 child 附加到节点并将其放在第一个 child 之前?即我想尝试附加一个新的 child 并将其按顺序推到顶部。
说,如果我有:
pugi::xml_node root;
pugi::xml_node level1 = root.append_child("Level1");
pugi::xml_node level2 = root.append_child("Level2");
pugi::xml_node level3 = root.append_child("Level3");
我能否以某种方式附加一个新节点 level4
并将其放在 XML 树中的 level1
节点之前?
您可以使用 root.insert_child_before("Level4", root.first_child())
.
它的评分者不寻常地为每个 child 设置了不同的标签名称。一种更常见的格式是让 children 都具有相同的名称并设置属性以将它们彼此区分开来。
一个如何做到这一点的例子:
int main()
{
pugi::xml_document doc;
pugi::xml_node root = doc.append_child("levels");
root.append_child("level").append_attribute("id").set_value("L01");
root.last_child().append_child("description").text().set("Some L01 stuff");
root.append_child("level").append_attribute("id").set_value("L02");
root.last_child().append_child("description").text().set("Some L02 stuff");
// now insert one before the first child
root.insert_child_before("level", root.first_child()).append_attribute("id").set_value("L00");
root.first_child().append_child("description").text().set("Some L00 stuff");
doc.print(std::cout);
}
输出:
<levels>
<level id="L00">
<description>Some L00 stuff</description>
</level>
<level id="L01">
<description>Some L01 stuff</description>
</level>
<level id="L02">
<description>Some L02 stuff</description>
</level>
</levels>
刚刚有人教我做 prepend_child
。仍然感谢 Galik 的建议。