Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why XPath does not work with xmlns attribute

I have the following XPath expression:

/configuration/properties

And this is my XML:

<configuration
    xmlns="http://www.ksharma.in/myXSD">
    <properties>
        <property key="a" value="1" />
        <property key="b" value="2" />
    </properties>
</configuration>

The XPath does not work. However If I change the name space from xmlns to xmlns:conf it works:

<configuration
    xmlns:conf="http://www.ksharma.in/myXSD">
    <properties>
        <property key="a" value="1" />
        <property key="b" value="2" />
    </properties>
</configuration>

Why is this so?

like image 393
Kshitiz Sharma Avatar asked May 06 '14 10:05

Kshitiz Sharma


1 Answers

Placing xmlns="http://www.ksharma.in/myXSD" on the root element of your XML puts the root and its descendants in the http://www.ksharma.in/myXSD namespace. This effectively means that all of the element names in your XML document are preceded by http://www.ksharma.in/myXSD. Yet, the elements stated in your XPath are not in the http://www.ksharma.in/myXSD namespace. Thus, your XPath matches nothing.

Placing xmlns:conf="http://www.ksharma.in/myXSD" instead on the root element merely defines a prefix for the http://www.ksharma.in/myXSD namespace but doesn't actually use it. The root element and its descendants remain in no namespace and are therefore able to be found by your XPath that also tests in no namespace. Thus, your XPath matches something.

See also How does XPath deal with XML namespaces?

like image 175
kjhughes Avatar answered Oct 14 '22 19:10

kjhughes