简体   繁体   中英

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM