/usr/share/doc/libxml2-devel/tutorial
NameSizeModeActions
images/-0755rm
apa.html21140644editdlrm
apb.html20260644editdlrm
apc.html30940644editdlrm
apd.html32320644editdlrm
ape.html30960644editdlrm
apf.html29490644editdlrm
apg.html30220644editdlrm
aph.html36000644editdlrm
api.html18990644editdlrm
ar01s02.html32980644editdlrm
ar01s03.html57180644editdlrm
ar01s04.html62230644editdlrm
ar01s05.html74220644editdlrm
ar01s06.html38490644editdlrm
ar01s07.html38660644editdlrm
ar01s08.html38940644editdlrm
ar01s09.html76030644editdlrm
includeaddattribute.c11360644editdlrm
includeaddkeyword.c13200644editdlrm
includeconvert.c18080644editdlrm
includegetattribute.c11710644editdlrm
includekeyword.c13510644editdlrm
includexpath.c14910644editdlrm
index.html59300644editdlrm
ix01.html25450644editdlrm
xmltutorial.pdf517090644editdlrm
Edit: /usr/share/doc/libxml2-devel/tutorial/ar01s04.html (6223B)
Retrieving Element Content

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.

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

1

Get the first child node of cur. At this point, cur points at the document root, which is the element "story".

2

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

1

Again we get the first child node.

2

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".

3

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]Note

Because xmlNodeListGetString allocates memory for the string it returns, you must use xmlFree to free it.