XPath - 按属性命名空间查找元素

时间:2009-02-09 19:37:11

标签: xml xpath namespaces

我正在尝试使用XPath来查找在给定命名空间中具有元素的所有元素。

例如,在下面的文档中,我想找到foo:bar和doodah元素

<?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>

我知道我可以使用以下XPath表达式来加载给定命名空间的所有属性

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

然而:

  • 这不会给我元素,只有属性和
  • 其中元素包含来自该命名空间的多个属性,此XPath将返回每个属性而不是每个元素的结果

是否有可能获得我想要的东西,或者我只需要收集属性并计算它们对应的唯一元素集?

编辑:Dimitre Novatchev给了我以下答案。我没有意识到你可以在这样的谓词中嵌套谓词:

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

具体来说,这表示“任何具有任何属性的元素都具有namespace-uri ='...'”

4 个答案:

答案 0 :(得分:25)

使用:

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

谓词两个条件是使用XPath or运算符编写的。

XPath表达式因此选择

的任何元素
  • 属于指定的命名空间

  • 具有属于指定命名空间的属性

答案 1 :(得分:4)

不确定这是不是您的意思,但只删除XPath中的1个字符,您将获得某个命名空间中的所有元素:

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

答案 2 :(得分:0)

你可以尝试

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

它将为您提供元素foo:bar和元素doodah(如果您在XML数据中将tal:quux更改为foo:quux):

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

是你想要的吗?

编辑:感谢您发现属性错误,现在更正了。

答案 3 :(得分:0)

你的XPath表达几乎是完美的。而不是要求属性“@ ”请求元素“”,它应该工作:

"//*[namespace-uri()='http://foo.example.com']"
相关问题