简体   繁体   中英

How to retrieve the xml value using the xpath?

My Scenario : I may get the different outputs which is shown below.I want to retrieve the "Units" tag value depends on Code tag.

Output1 :

<Riders>
<Rider>
  <Name>ALSP</Name>
  <Code>ALSP</Code>
  <Units>3</Units>
</Rider>
<Rider>
  <Name>Individual</Name>
  <Code>Select Type of Coverage</Code>
  <OptionCode>Individual</OptionCode>
  <IsFeature>true</IsFeature>
</Rider>
</Riders>

Output2 :

<Riders>
<Rider>
  <Name>AFO</Name>
  <Code>AFO</Code>
  <Units>6</Units>
</Rider>
<Rider>
  <Name>Individual</Name>
  <Code>Select Type of Coverage</Code>
  <OptionCode>Individual</OptionCode>
  <IsFeature>true</IsFeature>
</Rider>
</Riders>

I have tried below xpath but didn't worked out. Could anyone suggest me.

/Riders/Rider/Code[text()[contains(.,'AFO')]  or text()     [contains(.,'ALSP')]]/Units

Depending on if you want to get the node with regards to the root or just find any matching node, you could use something like...

*/Rider[Code[contains(.,'ALSP')]]/Units

Which will return you all the Units nodes which belong to any Rider node, which have a Code node, whose text contains ALSP

Of course you could also use...

*/Rider[Code[text() = 'ALSP']]/Units

If the Code must match exactly.

The above will find all the Units nodes of the Rider node anywhere in the document. If the position is important, you would need to replace */ with /Riders/ instead.

Now, if you want to find both ALSP and AFO , you could use something like...

*/Rider[Code[text() = 'ALSP' or text() = 'AFO']]/Units

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM