Not yet rated

Problem

An application needs to search an XML document to retrieve specific pieces of information.

Solution

ColdFusion provides the ability to use XML Path Language ( XPath ) to search an XML document using the XMLSearch function.

Detailed explanation

An XML document can provide a lot of data and many times and application may only need certain parts of that data. Using the XMLSearch function with an XPath expression can help get to the data that's needed quickly and efficiently.

First the application needs to have XML.  The XML can come from a webservice, reading a file, or any number of other places.  In this case it will be a hardcoded variable setup using the <cfsavecontent> tag.

<cfsavecontent variable="authorXML">
<authors>
     <author firstName="Kevin" lastName="Schmidt"
email="kevin.schmidt@authors.com" />
     <author firstName="Ed" lastName="Sullivan"
email="ed.sullivan@authors.com" />
     <author firstName="Jon" lastName="Schmidt"
email="jon.schmidt@authors.com" />
</authors>
</cfsavecontent>

This is a small piece of XML and a real XML file that had author information may have large amounts of other information that relates to the authors such as publishers, books, etc.  If the application only needs the authors information, using the XMLSearch function will allow the application to retrieve just the author information.

The XMLSearch function returns an array of any of the XML nodes that match the XPath expression.  If no matches are found an empty array is returned.

<cfset authors = XMLSearch( authorXML, "/authors/author" ) />

<cfdump var="#authors#" />

The above code produces the following: 

An application needs to search an XML document to retrieve specific pieces of information.

Perhaps the application needs to get down to an even deeper level and only show authors with the last name Schmidt.  This is done the same way as above, but with a different XPath expression.

<cfset authors = XMLSearch( authorXML,
"/authors/author[@lastName='Schmidt']" ) />

<cfdump var="#authors#" />

The above code produces the following: 

An application needs to search an XML document to retrieve specific pieces of information.

XPath is a very powerful way to search XML files and the above examples illustrate some of the basic ways to search.  ColdFusion give applications a simple way to use XPath with the XMLSearch function


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes