Wildcard Namespaces In XPath

November 1st, 2008 by bill · 7 Comments

»How to select an element in an XML document without having to deal with XPath namespaces. In otherwords, how to wildcard namespaces in XPath.

 

Select namespaced elements in XPath without specifying the namespace.

Every once in a while you need to get to an XML element that is tucked within some namespace or another, but you really are not in the mood to deal with namespaces. You really don’t want to mess with XmlNamespaceManager or its ilk; or maybe you only have XPath to work with.

When this comes up, it usually takes me a few moments to remember, but the magic is the local-name() function.

XML

<gw:bookstore xmlns:gw="http://www.moonbats.com/gw">
	<gw:book>
		<gw:title>Warming Up To The New Ice Age</gw:title>
		<gw:author>A. Nother Lemming</gw:author>
	</gw:book>
	<gw:book>
		<gw:title>The Sky Is Falling</gw:title>
		<gw:author>Chicken Little</gw:author>
	</gw:book>
	<gw:book>
		<gw:title>Glaciers Will Burn Us All</gw:title>
		<gw:author>Chicken Little</gw:author>
	</gw:book>
	<gw:book>
		<gw:title>Data: A Cookbook</gw:title>
		<gw:author>Grant Me Money</gw:author>
	</gw:book>
</gw:bookstore>

XPath

//*[local-name()='title']

This basically says to select any element where the local name, i.e. the element name minus the namespace, is equal to ‘title’.

This can be extended with other XPath functions. In the following example we want to get the titles of books by Chicken Little.

//*[ local-name() = 'title' and (../*[local-name() = 'author'
	and contains( text(), 'Chicken Little' ) ]) ]

Here we’re selecting elements with a local name of ‘title’ and a sibling element named author and where that sibling’s value contains ‘Chicken Little’.

This syntax is not as convenient as something like /*:title, but at least it does the trick.

Tags: Programming · XML

 

7 responses so far ↓

  • 1 Leo // Jun 8, 2010 at 10:39 am

    Nice article. I had a need to do transformations in different types of XML in a web-service and sometimes the soap request declares the elements in a different form. The most common example is when you create a call from soapUI.

    Anyway, good post

  • 2 bill // Jun 8, 2010 at 7:46 pm

    Thanks, Leo. Glad it was helpful.

  • 3 A grateful soul // Mar 4, 2011 at 9:53 am

    Thanks, saved me some hours of head scratching

  • 4 falseawake // Apr 27, 2011 at 2:50 am

    Your article made my day, thanks!

    My Problem was: Axis2 uses alternating namespaces in SOAP-Responses. With two or more Test Steps in SoapUI i had to find values from preceding XML Responses.

  • 5 Fi // May 29, 2011 at 9:15 am

    Very nice! This local-name thing rocks!
    Thanx!

  • 6 mahesh // Aug 30, 2011 at 5:11 am

    will xpath local-name() work when browser is in quirks mode?

  • 7 Mellowg // Oct 6, 2011 at 10:01 pm

    Thanks man! Saved me hours of hair-pulling and made my app future proof.

    Awesome, awesome tip

Leave a Comment


− 8 = one