【问题标题】:xpath to find a node with optional attributexpath 查找具有可选属性的节点
【发布时间】:2021-03-07 03:32:08
【问题描述】:

我想在多个 XML 文件中搜索具有可选属性的节点。缺少我正在寻找的属性的文件没有声明它所属的命名空间。我正在使用简单的 XPath 进行搜索,如下例所示:

这里我对nodeother_attribute感兴趣:

<?xml version="1.0" encoding="UTF-8"?>
<otherfile xmlns:xs="something" xmlns:optional="something_else">
  <node attribute = "hohoho" optional:other_attribute= "mary Xmass">
  </node>
</otherfile>

我正在使用 XPath //@optional:other_attribute 匹配它。但是,当尝试在以下文件中执行相同操作时:

<?xml version="1.0" encoding="UTF-8"?>
<file xmlns:xs="something">
    <node attribute = "hohoho">
    </node>
</file>

搜索失败,因为命名空间optional 未在第二个示例文件中声明。有没有办法使用 Xpath 语法对属性进行条件搜索?

【问题讨论】:

  • 您想使用@optional:other_attribute 还是@other_attribute 获取节点?或者您想使用@optional:other_attribute@attribute 获取节点?你能澄清一下吗?从描述中看不清楚。
  • 抱歉没有解释得很好,我想做的是获取@optional:other_attributeonly如果它存在。我的问题是,如果没有声明命名空间而不是什么都不返回(节点不存在),那么 Xpath 查询将失败

标签: xml xpath


【解决方案1】:

这应该可以工作

//@*[name()="optional:other_attribute"]

【讨论】:

  • 感谢@DonnyFlaw,但是我尝试了//@*[local-name()=("other_attribute")],它似乎大部分时间都有效。如果我理解正确,它将匹配任何名为 other_attribute 的属性,无论命名空间如何。因此,当我有来自其他名称空间的同名属性时,它也会匹配它们。有没有办法避免这样做?
  • @DiamantisSellis 试试这个//@*[name()="optional:other_attribute"]
【解决方案2】:

如果我理解正确,最简单的方法是将表达式切换为local-name()。用表达式

//*[@*/local-name()="other_attribute"]

将在第一个示例中选择正确的节点,而在另一个示例中不选择任何节点。

【讨论】:

  • 需要注意的是,这个XPath只在XPath 2.0或更高版本有效。
猜你喜欢
  • 2013-11-30
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多