Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select node without namespace with XPath

I have a xml like

<root xmlns:ns1="http://foo">
    <ns1:child1>Text</ns1:child1>
    <ns1:child2>Number</ns1:child2>
</root>

Now I get this from different persons, so that for example person 2 sends me another message with the same structure like

<root xmlns:anotherNs="http://foo">
    <anotherNs:child1>Another Text</anotherNs:child1>
    <anotherNs:child2>Another Number</anotherNs:child2>
</root>

So the only difference is the name of the namespace. How can I select the content of child2 for both xml's with one XPath expression?

Something like "/root/child2" or "//child2" did not work.

like image 380
Hauke Avatar asked Feb 28 '13 15:02

Hauke


People also ask

What does node () do in XPath?

node() matches any node (the least specific node test of them all) text() matches text nodes only. comment() matches comment nodes. * matches any element node.

What is namespace node in XPath?

Introduction to XPath namespace. In an XML document, namespaces are used to provide uniquely named components and attributes. A namespace is made up of two parts: a prefix and a URL. This indicates the location of a document that defines the namespace in question.

How to avoid naming conflicts in XML?

Name conflicts in XML can easily be avoided using a name prefix. In the example above, there will be no conflict because the two <table> elements have different names.


2 Answers

Use the local-name() function like so:

//*[local-name()='child2']
like image 147
JWiley Avatar answered Oct 23 '22 12:10

JWiley


You can bind any prefix you like (say banana) to the namespace "http://foo", and the expression /root/banana:child2 will find the child2 element, regardless what namespace prefix has been used in the source document. Only the namespace URI has to match.

like image 20
Michael Kay Avatar answered Oct 23 '22 12:10

Michael Kay