Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath and XML: Multiple namespaces

So I have a document that looks like

<a xmlns="uri1" xmlns:pre2="uri2">
 <b xmlns:pre3="uri3">
   <pre3:c>
     <stuff></stuff>
     <goes></goes>
     <here></here>
   </pre3:c>
   <pre3:d xmlns="uri4">
     <under></under>
     <the></the>
     <tree></tree>
   </pre3:d>
  </b>
</a>

I want an xpath expression that will get me <under>.

This has a namespaceURI of uri4.

Right now my expression looks like:

//ns:a/ns:b/pre3:d/pre4:under

I have the namespace manager add 'ns' for the default namespace (uri1 in this case) and I have it defined with pre2, pre3, and pre4 for uri2, uri3, and uri4 respectively.

I get the error "Expression must evaluate to a node-set."

I know that the node exists. I know that everything up until the pre4:under in my xpath works fine as I use it in the rest of the document with no issues. It's the additional pre4:under that causes the error, and I'm not sure why.

Any ideas?

Thanks.

Resolution:

Thank you all for your insistence that it's correct--it was. But... in my code I had "pre4" as "64" (a variable) and it didn't like an integer for a prefix. Changing it to "d" + myintvariable worked.

like image 486
emragins Avatar asked Feb 25 '11 22:02

emragins


People also ask

Can XML have multiple namespaces?

When you use multiple namespaces in an XML document, you can define one namespace as the default namespace to create a cleaner looking document. The default namespace is declared in the root element and applies to all unqualified elements in the document. Default namespaces apply to elements only, not to attributes.

How to handle namespace in XPath?

XPath queries are aware of namespaces in an XML document and can use namespace prefixes to qualify element and attribute names. Qualifying element and attribute names with a namespace prefix limits the nodes returned by an XPath query to only those nodes that belong to a specific namespace.

How to write XPath with namespace?

There is no method to connect a namespace prefix to a namespace in XPath. The hosting library can provide these services. It is strongly advised that we take advantage of those features and create namespace prefixes that may be used to qualify XML element and attribute names as needed.

What is local name () in XPath?

The local-name function returns a string representing the local name of the first node in a given node-set.


1 Answers

My guess is that there may be a bug with the implementation that you are using to navigate the XML. Using SketchPath, the following XPath navigated to the node successfully:

/def:a/def:b/pre3:d/def2:under

Could you try specifying different prefixes for the namespaces in the XPath? Otherwise, if performance isn't really an issue, and it's a unique node, you could just try //under

like image 182
Richard Nienaber Avatar answered Jan 04 '23 08:01

Richard Nienaber