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

时间:2017-08-04 09:46:17

标签: java xml 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(id来获取folderInstance 2017-08-04-04.22.02.446460F01值的Xpath(在本例中为//createdInstances/folderInstance@id )。我尝试使用下面的表达式,但它不起作用。

display: flex

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

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

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

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

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

如果您正在使用Java this SO posting,则会演示如何将 NamespaceContext 添加到XPath表达式中。它还显示了另一种(不太精确)的方法,只匹配元素的局部部分,如下所示:

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