user3214224 user3214224 - 13 days ago 5
C++ Question

How to retrieve node and particular element string from xml file in C++ using libxml2 by using xpath?

How to retrieve text value in c++ using libxml?

Here is the XML:

<?xml version="1.0" encoding="UTF-8"?>
<Help xmlns="http://www.example.org/HelpFileStructure" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/HelpFileStructure HelpFileStructure.xsd ">
<Text>dfgdfg</Text>
</Help>


Code:

void Help::HelpName()
{
string Help_text;
parser.parse_file(XmlFileName);
Node* root = parser.get_document()->get_root_node();
NodeSet result = root->find("/Help/Text");
Element *first_element = (Element *)result.at(0);
Help_text = first_element->get_child_text()->get_content();
}

Answer

Use this:

NodeSet result = root->find("//*[local-name()='Help']/*[local-name()='Text']");

That gets a node set where each node is an element named Text, regardless of what namespace the element is in, that’s a child of any element named Help, regardless of what namespace it’s in.

If you only want Help and Text elements in the http://www.example.org/HelpFileStructure namespace, and want to ignore any Text and Help elements the document might have that are in some other namespace, then you can do use the namespace-uri() function like this:

NodeSet result = root->find("//*[local-name()='Help' and namespace-uri()='http://www.example.org/HelpFileStructure']/*[local-name()='Text' and namespace-uri()='http://www.example.org/HelpFileStructure']");