Ashok.N
Ashok.N

Reputation: 1391

Extracting value through Xpath expression when there are namespaces

I have the below input 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>

I need to get Xpath for id value of folderInstance using java(i.e 2017-08-04-04.22.02.446460F01 in this case). I tried with the below expression, but it's not working.

//createdInstances/folderInstance@id

Any help would be appreciated.

Upvotes: 0

Views: 46

Answers (1)

zx485
zx485

Reputation: 29022

You forgot the namespace of the matching nodes. Create a namespace for the XPath (like this in XSLT)

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

and add the namespace prefixes to the element's names. Also add a / before selecting an attribute.

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

If you're using Java this SO posting shows how to add a NamespaceContext to your XPath expression. It also shows another (less precise) approach to only match the local parts of the elements which would look like this:

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

Upvotes: 1

Related Questions