how to ignore namespaces with XPath

kostja picture kostja · Dec 14, 2010 · Viewed 93.4k times · Source

My goal is to extract certain nodes from multiple xml files with multiple namespaces using XPath. Everything works fine as long as i know the namespace URIs. The namespace name itself remains constant, but the Schemas (XSD) are sometimes client-generated i.e. unknown to me. Then i am left with basically three choices :

  1. use just one schema for the namespace, hoping nothing goes wrong (can i be sure?)

  2. get the children nodes of the document and look for the first node with a namespace URI, hoping its there and just use the URI , hoping its the correct one. can go wrong for multiple reasons

  3. somehow tell xpath : "look, i dont care about the namespaces, just find ALL nodes with this name, i can even tell you the name of the namespace, just not the URI". And this is the question here...

This is not a reiteration of numerous "my xpath expression doesnt work because i am not aware of namespace awareness" questions as found here or here. I know how to use namespace awareness. Just not how to get rid of it.

Answer

Dirk Vollmar picture Dirk Vollmar · Dec 14, 2010

You can use the local-name() XPath function. Instead of selecting a node like

/path/to/x:somenode

you can select all nodes and filter for the one with the correct local name:

/path/to/*[local-name() = 'somenode']