Using XPath

XPath expressions provide a powerful way of addressing parts of an XML document. The W3C XPath recommendation can be found at http://www.w3.org/TR/xpath. Many good XPath tutorials can be found on the web, such as http://www.w3schools.com/xpath/.

Essentially, XPath expressions allow you to search a document for nodes that match a given criteria. Note that it finds nodes: this means it can locate not only elements, but attributes, text content, etc.

To use XPath in the xmlTree API, a XPath object is first created with xmlTreeNewXPath(). If any namespaces are needed in the expression, they must be registered with the xpath object via xmlTreeXPathRegisterNs(). XPath expressions can then be executed with xmlTreeXPathExecute()


EXAMPLE

<capture>
<rootNode><name>John Doe</name><age>34</age><iq>34</iq></rootNode>
</capture><$xmlRaw = $ret>
<$doc = (xmlTreeNewDocFromString( $xmlRaw, 'XML_PARSE_NOBLANKS'))>
<$xpath = (xmlTreeNewXPath($doc))>
<!-- this selects the 'name' node -->
<$name = (xmlTreeXPathExecute($xpath, "/rootNode/name"))>
<$nameText = (xmlTreeGetContent($name))>
name is $nameText
<!-- this selects all nodes whose content is 34 -->
<$nodes = (xmlTreeXPathExecute($xpath, "//*[.='34']"))>
The following elements have the value 34:
<loop $nodes>
    <$ret = (xmlTreeGetName($nodes))>
    $ret
</loop>

If you have XML data stored in the field of a database, you can use xmlTreeQuickXPath() to easily extract data from it for comparison:

select name from books where xmlTreeQuickXPath(data, '/rootNode/item') = 'Bill'

See the sample xmlTree08_XPath for more and larger examples using XPath and QuickXPath.


SEE ALSO
xmlTreeNewXPath, xmlTreeXPathExecute, xmlTreeXPathRegisterNs, xmlTreeQuickXPath


Copyright © Thunderstone Software     Last updated: Apr 15 2024
Copyright © 2024 Thunderstone Software LLC. All rights reserved.