Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

xml - How to find elements by attribute namespace in XPath

I'm trying to use XPath to find all elements that have an element in a given namespace.

For example, in the following document I want to find the foo:bar and doodah elements:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:foo="http://foo.example.com">
  <foo:bar quux="value">Content</foo:bar>
  <widget>Content</widget>
  <doodah foo:quux="value">Content</doodah>
</root>

I know I can use the following XPath expression to load all attributes from a given namespace:

"//@*[namespace-uri()='http://foo.example.com']"

However:

  • This doesn't give me the elements, just the attributes.
  • Where elements contain multiple attributes from that namespace, this selector will return a result per-attribute rather than per-element

Is it possible to get what I want, or do I have to gather the attributes and calculate the unique set of elements they correspond to?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use:

//*[namespace-uri()='yourNamespaceURI-here'
   or
    @*[namespace-uri()='yourNamespaceURI-here']
   ]

the predicate two conditions are or-ed with the XPath or operator.

The XPath expression thus selects any element that either:

  • belongs to the specified namespace.
  • has attributes that belong to the specified namespace.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...