Using an XPath wildcard

Posted on Tuesday, September 28th, 2010 at 7:45 pm

In the case that you need to use XPath to retrieve an XML node, but are missing some piece of information you can use the ‘*’ as a wildcard in the XPath expression. Let’s take for example an application where a request for a certain type of house can be made and a set of XML representing that house and its details is returned. So let’s say the application requests a ‘Ranch House’. The XML returned looks like:

<House>
	<RanchHouse>
		<Floors>1</Floors>
		<Acres>8</Acres>
		<Basement>true</Basement>
	</RanchHouse>
</House>

And if we request a ‘Georgian House’ we would get:

<House>
	<GeorgianHouse>
		<Floors>3</Floors>
		<Acres>3</Acres>
		<Basement>false</Basement>
	</GeorgianHouse>
</House>

Notice that the child node of ‘House’ is different in both cases. While this may not be ideal XML it is valid and may be encountered. So we encounter this and we want to write a single XPath expression that will retrieve the number of floors for any house that is returned to us. In the expression where the the child node of ‘House’ is referenced we can use a wildcard to essentially bypass it and access its child nodes. If using the Coldfusion xmlSearch() function, our expression would look like:

<cfset variables.floors = xmlSearch(variables.myXmlObject, "/:House/*/:Floors") />

Use of the wildcard can go much further than this, but I do love how simple it is to skip over an xml node if its an unknown.

CategoryXML

Leave a Reply

*
(Won't be published) *