How to replace a nodes pcdata or text using pugixml

3.4k views Asked by At

I am looking for an elegant solution to replacing a nodes pcdata using pugixml (version 1.6). For example, iterating through a node set and updating the child value to something.

pugi::xpath_node_set nodes = document.select_nodes("//a");

for (auto it = nodes.begin(); it != nodes.end(); it++)
{
    std::cout << "before : " << it->node().child_value() << std::endl;

    // SOME REPLACE GOES HERE

    std::cout << "after  : " << it->node().child_value() << std::endl;
}

I have used the:

it->node().append_child(pugi::node_pcdata).set_value("foo");

but as the name suggests it just appends the data but I can't find any functions along the lines of:

it->node().remove_child(pugi::node_pcdata);

Another note is that the attributes on the node are important and should remain unchanged.

Thanks for your help.

1

There are 1 answers

1
zeuxcg On BEST ANSWER

xml_text object is made for this purpose (among others):

std::cout << "before : " << it->node().child_value() << std::endl;

it->node().text().set("contents");

std::cout << "after  : " << it->node().child_value() << std::endl;

Note that you can also use text() instead of child_value(), e.g.:

xml_text text = it->node().text();

std::cout << "before : " << text.get() << std::endl;

text.set("contents");

std::cout << "after  : " << text.get() << std::endl;

This page has more details: http://pugixml.org/docs/manual.html#access.text