tags:

views:

272

answers:

6

I'm having trouble selecting elements that are part of an specific namespace. My xpath expression works in XMLSpy but fails when using the Xalan libraries..

<item>
   <media:content attrb="xyz">
     <dcterms:valid>VALUE</dcterms:valid>
  </media:content>
</item>

My expression ./item/media:content/dcterms:valid. I've already added both namespace definitions to my xslt. Again, this selects the right values in XMLSpy but fails when running through xalan library.

Any ideas?

A: 

Have you tried to define the namespace of the XML blob?

<item xmlns:dcterms="http://dcterms.example" xmlns:media="http://media.example"&gt;
   <media:content attrb="xyz">
     <dcterms:valid>VALUE</dcterms:valid>
  </media:content>
</item>

i.e.

  • xmlns:dcterms="http://dcterms.example"
  • xmlns:media="http://media.example"
codemeit
It's already in the source XML.
TChen
A: 

Perhaps XMLSpy has implemented the 2.x XSLT spec of which I believe XPath is a part. Xalan on the other hand is still 1.x.

dacracot
There's an XPath 1.0 and an XPath 2.0 spec, which correspond (basically) with the releases of XSLT 1.0 and XSLT 2.0. The XPath he's attempting is valid XPath 1.0.
James Sulak
A: 

In what context are you trying to evaluate your XPath from? (For example, an XSLT?) If is the root element, you might try removing the leading ".": "/item/media:content/dcterms:valid." If there is a series of items, you might try adding another slash at the beginning: "//item/media:content/dcterms:valid." That will select all the items in the document that match that criteria, no matter where in the document structure they are located.

James Sulak
A: 

Prefixes in XML are meaningless until they're bound to a certain namespace, and this is also true for XPath expressions – it won't match simply because you've used same prefix.

You must create your own PrefixResolver class which will give full namespace URIs for prefixes you have in your XPath expression.

porneL
+1  A: 

You'll need to implement a org.apache.xml.utils.PrefixResolver to map the prefix to namespace URI, and then pass an instance to the XPath instance you use. This will allow you to use different prefixes in your XPath expressions from those in your documents (which you might not control).

For example, you could create an implementation that uses a pair of maps (one to map from prefix -> namespace URI, and one from URI to prefix).

In JAXP, the equivalent interface to implement is javax.xml.namespace.NamespaceContext.

Michael Hall
A: 

You could try a XPath select on the local-name and (optionally) give a namespace URI. And example:

/*[local-name()='NewHireList' and namespace-uri()='http://BRE.NewHireList']/*[local-name()='Record' and namespace-uri()='']

See this page for more, or google on local-name and XPath.

extraneon