Monday, August 08, 2005
Accessing Default Namespace with XPath
I was wondering if there is a way in XPath to access XML elements specified with a default namespace. For example, here is an XML using namespace "ns1" and a default namespace:
Well, here is one that will do the job. The trick is simply to make use of the property that the local name of an element is equal to it's full name only if the element is in the default namespace.
How can we specify an XPath expression to access element C (in the default namespace) ? The naive solution:
<ns1:A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://hanson/Dadidadida">
xmlns:ns1="http://hanson/Dadidadida/ns1"
>
<ns1:B><C/></ns1:B>
</ns1:A>
/ns1:A/ns1:B/Cwon't work. Many places (such as this) seem to indicate that there is just no way to do it. But is that really the case ?
Well, here is one that will do the job. The trick is simply to make use of the property that the local name of an element is equal to it's full name only if the element is in the default namespace.
/ns1:A/ns1:B/*[local-name()=name()][name()='C']or simply,
/ns1:A/ns1:B/*[name()='C']Why XPath doesn't have something simpler is beyond me.