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

753 views Asked by At

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

XML file:

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

There are 1 answers

0
Sprotty On BEST ANSWER

This XmlSoft has a great set of examples for libxml2 demonstrating how to do most common tasks.

xmlDoc *doc = NULL;
xmlNode *root_element = NULL;

if (argc != 2)
    return(1);

/*
 * this initialize the library and check potential ABI mismatches
 * between the version it was compiled for and the actual shared
 * library used.
 */
LIBXML_TEST_VERSION

/*parse the file and get the DOM */
doc = xmlReadFile(argv[1], NULL, 0);

if (doc == NULL) {
    printf("error: could not parse file %s\n", argv[1]);
}

/*Get the root element node */
root_element = xmlDocGetRootElement(doc);

print_element_names(root_element);

/*free the document */
xmlFreeDoc(doc);

/*
 *Free the global variables that may
 *have been allocated by the parser.
 */
xmlCleanupParser();


static void
print_element_names(xmlNode * a_node)
{
    xmlNode *cur_node = NULL;

    for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
        if (cur_node->type == XML_ELEMENT_NODE) {
            printf("node type: Element, name: %s\n", cur_node->name);
        }

        print_element_names(cur_node->children);
    }
}