简体   繁体   中英

Xpath to extract elements from nodes based on element condition

I have an xml for extracting elements -

<?xml version="1.0"?>
<Carmodels>
  <Cars>
    <id>1223</id>
    <cartype>Sedan</cartype>
    <price>1000</price>
  </Cars>
  <Cars>
    <id>1234</id>
    <car>Sports</car>
    <price>2500</price>
  </Cars>
  <Cars>
    <id>1123</id>
    <car>Taxi</car>
    <price>9000</price>
  </Cars>
  <Cars>
   <id>1223</id>
    <car>Taxi</car>
    <price>1000</price>
   </Cars>
</Carmodels>

Now I would need to extract <price> tags from <cars> node where <car> = Taxi. I need only Xpath for extracting the price.

Sample output:

 9000
 1000

We need Xpath only to execute through Java.

Please try the following XPath expression. It converts the car tag value to lower case. So both Taxi and taxi are taken into account.

XPath

/Carmodels/Cars[lower-case(car)="taxi"]/price

XPath 1.0 expressions which supports the word taxi written with lowercase or uppercase characters:

//Cars[car[translate(.,"tT","tt")="taxi"]]/price
//car[translate(.,"tT","tt")="taxi"]/following-sibling::price

Output: 2 nodes

<price>9000</price>
<price>1000</price>

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