I find Xpath very powerul for searching through a XML document. I have used it extensively in some of my projects and it might be worth it to post some of the examples here. For this example, I have used the books.xml sample xml file which can be found here.

Following are some examples of what we can do with Xpath in Coldfusion. I have tried to keep the variable names self-explanatory so it should easy to figure out which statement is doing what.

<cffile action="read" file="#ExpandPath('books.xml')#" variable="myBooks">
<cfset myxml="XmlParse(myBooks)">
<cfscript>
allbooks = XmlSearch(myXml, "catalog/book");

firstBook = XmlSearch(myXml, "catalog/book[1]");
lastBook = XmlSearch(myXml, "catalog/book[last()]");

secondLastBook = XmlSearch(myXml, "catalog/book[last()-1]");
countBooks = XmlSearch(myXml, "count(catalog/book)");

sumPriceAllBooks = XmlSearch(myXml,sum(catalog/book/price)");
bookAuthors = XmlSearch(myXml,"catalog/book/author");

searchByTitle = XmlSearch(myXml,catalog/book[title='Midnight Rain']/title");
searchByAuthor = XmlSearch(myXml,catalog/book[genre='Fantasy']/title");

searchById = XmlSearch(myXml,catalog/book[@id='bk109']/title");
</cfscript>

If you want to try this code out, make sure you download the books.xml and keep it in the same folder as you keep the above code in.

More Xpath samples can be found here .