Search code examples
c++xmlxpathpugixml

Simple XPath program doesn't work


XML file tree.xml:

<?xml version="1.0"?>
<mesh name="mesh_root">
    some text
    <![CDATA[someothertext]]>
    some more text
    <node attr1="value1" attr2="value2" />
    <node attr1="value2">
        <innernode/>
    </node>
</mesh>

I want to get the <node> items. And then their attr1 values.

C++ code:

#include "pugixml.hpp"
#include <iostream>

using namespace pugi;
int main()
{
    xml_document doc;

    xml_parse_result result = doc.load_file("tree.xml");

    xpath_query q("node");
    xpath_node_set ns = doc.select_nodes(q);
    std::cout << ns.size() << std::endl;
}

I supposed that the result should be 2, but for some reason it is 0. What's wrong?


Solution

  • There were 2 errors in my code:

    1. To match all the <node> elements in the document, we need to use the following XPath expression: "//node"

    2. Different syntax to run XPath query:


    xpath_query q("//node");
    xpath_node_set ns = q.evaluate_node_set(doc);
    std::cout << ns.size() << std::endl;
    

    Prints 2.