TChen
TChen

Reputation: 51

how to select an element within a specific namespace?

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 is ./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?

Upvotes: 2

Views: 1299

Answers (6)

extraneon
extraneon

Reputation: 23950

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.

Upvotes: 0

Michael Hall
Michael Hall

Reputation: 135

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.

Upvotes: 1

Kornel
Kornel

Reputation: 100070

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.

Upvotes: 0

James Sulak
James Sulak

Reputation: 32437

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.

Upvotes: 0

dacracot
dacracot

Reputation: 22338

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.

Upvotes: -1

Ray Lu
Ray Lu

Reputation: 26638

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

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

i.e.

  • xmlns:dcterms="http://dcterms.example"
  • xmlns:media="http://media.example"

Upvotes: 0

Related Questions