1 ˆl–Ü4ý()¨‰P@Š7jãN©‹FÿÇ 0ÆÅ+ˆl–Ðz¾” Ja,j�nà_¸!)‹FÿÈ ƒu¦Å_‡I|¥‰ÓMÈÇUsing XPath to Retrieve Element Content

Using XPath to Retrieve Element Content

In addition to walking the document tree to find an element, Libxml2 includes support for use of XPath expressions to retrieve sets of nodes that match a specified criteria. Full documentation of the XPath API is here.

XPath allows searching through a document for nodes that match specified criteria. In the example below we search through a document for the contents of all keyword elements.

[Note]Note

A full discussion of XPath is beyond the scope of this document. For details on its use, see the XPath specification.

Full code for this example is at Appendix D, Code for XPath Example.

Using XPath requires setting up an xmlXPathContext and then supplying the XPath expression and the context to the xmlXPathEvalExpression function. The function returns an xmlXPathObjectPtr, which includes the set of nodes satisfying the XPath expression.

	xmlXPathObjectPtr
	getnodeset (xmlDocPtr doc, xmlChar *xpath){
	
	1xmlXPathContextPtr context;
	xmlXPathObjectPtr result;

	2context = xmlXPathNewContext(doc);
	3result = xmlXPathEvalExpression(xpath, context);
	4if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
		xmlXPathFreeObject(result);
                printf("No result\n");
		return NULL;
      

1

First we declare our variables.