当存在命名空间时,通过 Xpath 表达式提取值



我有以下输入xml:

<?xml version="1.0" encoding="UTF-8"?>
<createdInstances xmlns="http://www.company.com/awd/rest/v1" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<folderInstance recordType="folder" id="2017-08-04-04.22.02.446460F01">
<link rel="form" type="application/vnd.company.awd+xml" href="awdServer/awd/services/v1/instances/2017-08-04-04.22.02.446460F01/form" />
<link rel="history" type="application/vnd.company.awd+xml" href="awdServer/awd/services/v1/instances/2017-08-04-04.22.02.446460F01/history" />
</folderInstance>
</createdInstances>

我需要使用 java 获取 XpathidfolderInstance的值(即在这种情况下是2017-08-04-04.22.02.446460F01(。我尝试使用以下表达式,但它不起作用。

//createdInstances/folderInstance@id

任何帮助将不胜感激。

您忘记了匹配节点的命名空间。为 XPath 创建一个命名空间(就像在 XSLT 中一样(

xmlns:com="http://www.company.com/awd/rest/v1"

并将命名空间前缀添加到元素的名称中。在选择属性之前,还要添加/

//com:createdInstances/com:folderInstance/@id

如果您使用的是 Java,则此 SO 帖子显示了如何将NamespaceContext添加到 XPath 表达式中。它还显示了另一种(不太精确(仅匹配元素的局部部分的方法,如下所示:

//*[local-name()='createdInstances']/*[local-name()='folderInstance']/@id

最新更新