skip to Main Content

I have a sample XML as shown below.

<cars>
   <car id="001">
    <name>FirstCar</name>
    <relationships>
      <relationship type="Owned By">Mike</relationship>
    <relationships>
   </car>
   <car id="002">
    <name>SecondCar</name>
    <relationships>
      <relationship type="Owned By">Jake</relationship>
    <relationships>
   </car>
   <car id="003">
   <name>ThirdCar</name>
    <relationships>
      <relationship type="Leased By">Jason</relationship>
    <relationships>
   </car>
</cars>

I am trying to utilize Java to create an XPath query which lists the ids of all the cars that have owners. I have tried the 2 xpath expressions below but they both return null:

xpathExpression = "/cars/car/relationships/relationship[@type='Owned By']/@id";
xpathExpression = "/cars[./relationships/relationship[@type='Owned By']]/@id";

What else can I use as an xpath expression to list the IDs for all the owned cars?

3

Answers


  1. These xpaths will find attributes as requested

    //car[relationships/relationship[@type="Owned By"]]/@id
    //relationship[@type="Owned By"]/ancestor::car/@id
    
    Login or Signup to reply.
  2. Simply use

    /cars/car/relationships/relationship[@type='Owned By']/../../@id
    
    Login or Signup to reply.
  3. I think the most straightforward is

    //car[relationships/relationship/@type="Owned By"]/@id
    

    but you’ve been given other options that are equally correct technically.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search