pugixml-获取所有文本节点(PCDATA),而不仅仅是第一个

joz*_*yqk 3 c++ xml pugixml

目前,如果我尝试解析

<parent>
    First bit of text
    <child>
    </child>
    Second bit of text
</parent>
Run Code Online (Sandbox Code Playgroud)

我只得到First bit of text

parent.text().get()
Run Code Online (Sandbox Code Playgroud)

抓取所有文本节点的正确方法是parent什么?

  1. 为此有一个很好的实用程序功能吗?
  2. 遍历所有孩子怎么做?

zeu*_*xcg 6

没有将所有文本连接在一起的函数。如果要获取文本节点子代的列表,则有两个选择:

  1. XPath查询:

    pugi::xpath_node_set ns = parent.select_nodes("text()");
    
    for (size_t i = 0; i < ns.size(); ++i)
        std::cout << ns[i].node().value() << std::endl;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 带类型检查的手动迭代:

    for (pugi::xml_node child = parent.first_child(); child; child = child.next_sibling())
        if (child.type() == pugi::node_pcdata)
            std::cout << child.value() << std::endl;
    
    Run Code Online (Sandbox Code Playgroud)

请注意,如果可以使用C ++ 11,则第二个选项可能更简洁:

for (pugi::xml_node child: parent.children())
    if (child.type() == pugi::node_pcdata)
        std::cout << child.value() << std::endl;
Run Code Online (Sandbox Code Playgroud)

(当然,您也可以使用range for来遍历xpath_node_set)