user5224720
user5224720

Reputation:

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

How do you append a new child to a node and place it prior to the first child? i.e. I want to try and append a new child and push it to the top in order.

Say, if I have:

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");

Can I somehow append a new node, level4 and have it before the level1 node in the XML tree?

Upvotes: 2

Views: 1858

Answers (2)

user5224720
user5224720

Reputation:

Someone just showed me to do prepend_child instead. Still thanks Galik for the suggestion though.

Upvotes: 1

Galik
Galik

Reputation: 48615

You can use root.insert_child_before("Level4", root.first_child()).

Its rater unusual to have a different tag name for each child though. A more common format would be to have the children all with the same name and set the attributes to differentiate them from one another.

An example of how this can be done:

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);
}

Output:

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

Upvotes: 1

Related Questions