【发布时间】:2021-03-07 03:32:08
【问题描述】:
我想在多个 XML 文件中搜索具有可选属性的节点。缺少我正在寻找的属性的文件没有声明它所属的命名空间。我正在使用简单的 XPath 进行搜索,如下例所示:
这里我对node的other_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 查询将失败