Retrieving Element Content
Prev |  | Next

## Retrieving Element Content

Retrieving the content of an element involves traversing the document tree until you find what you are looking for. In this case, we are looking for an element called "keyword" contained within element called "story". The process to find the node we are interested in involves tediously walking the tree. We assume you already have an xmlDocPtr called `doc` and an xmlNodPtr called `cur`.

    	cur = cur->xmlChildrenNode;
    	while (cur != NULL) {
    		if ((!xmlStrcmp(cur->name, (const xmlChar *)"storyinfo"))){
    			parseStory (doc, cur);
    		}

    	cur = cur->next;
    	}

| Get the first child node of `cur`. At this point, `cur` points at the document root, which is the element "story".
| This loop iterates through the elements that are children of "story", looking for one called "storyinfo". That is the element that will contain the "keywords" we are looking for. It uses the libxml string comparison function, `xmlStrcmp`. If there is a match, it calls the function `parseStory`.

    void
    parseStory (xmlDocPtr doc, xmlNodePtr cur) {

    	xmlChar *key;
    	 cur = cur->xmlChildrenNode;
    	 while (cur != NULL) {
    	    if ((!xmlStrcmp(cur->name, (const xmlChar *)"keyword"))) {
    		    key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
    		    printf("keyword: %s\n", key);
    		    xmlFree(key);
     	    }
    	cur = cur->next;
    	}
        return;
    }

| Again we get the first child node.
| Like the loop above, we then iterate through the nodes, looking for one that matches the element we're interested in, in this case "keyword".
| When we find the "keyword" element, we need to print its contents. Remember that in XML, the text contained within an element is a child node of that element, so we turn to `cur->xmlChildrenNode`. To retrieve it, we use the function `xmlNodeListGetString`, which also takes the `doc` pointer as an argument. In this case, we just print it out.
| Note
Because `xmlNodeListGetString` allocates memory for the string it returns, you must use `xmlFree` to free it.

Prev | Up | Next
Parsing the file | Home | Using XPath to Retrieve Element Content