C++pugiXML,在节点的第一个子节点之前附加一个子节点

C++ pugiXML, Append a child before the first child in a node

本文关键字:子节点 一个 节点 C++pugiXML 第一个      更新时间:2023-10-16

如何将新的子节点附加到节点并将其放置在第一个子节点之前?即,我想尝试附加一个新的子项,并按顺序将其推到顶部。

说,如果我有:

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())

然而,每个孩子都有一个不同的标签名,这是不寻常的。一种更常见的格式是让所有子项都具有相同的名称,并设置属性以将它们彼此区分开来。

如何做到这一点的一个例子:

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的建议。