如何使用 pugixml 替换节点 pcdata 或文本

How to replace a nodes pcdata or text using pugixml

我正在寻找使用 pugixml(版本 1.6)替换节点 pcdata 的优雅解决方案。例如,遍历节点集并将子值更新为某物。

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

我用过:

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

但顾名思义,它只是附加数据,但我找不到任何类似以下内容的函数:

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

另外需要注意的是,节点上的属性很重要,应该保持不变。

感谢您的帮助。

xml_text 对象是为此目的而制作的(除其他外):

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

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

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

请注意,您也可以使用 text() 代替 child_value(),例如:

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

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

text.set("contents");

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

此页面有更多详细信息:http://pugixml.org/docs/manual.html#access.text