Spring
Spring

Reputation: 11835

Xpath query help

In Xpath how can I query if I'm looking for the child's age and name whom has NO grandchild

 <documentRoot>
 <parent name="data" >

  <child id="1"  name="alpha" >
   <anotherchild>
     <age>20</age>
     <grandchild/>
   </anotherchild>
  </child>

  <child id="2"  name="beta" >
   <anotherchild>
     <age>50</age>
     <grandchild id="2.1"  name="beta-alpha" ></grandchild>
     <grandchild id="2.2"  name="beta-beta" ></grandchild>
   </anotherchild>
  </child>

 </parent>
</documentRoot>

Upvotes: 0

Views: 76

Answers (1)

cordsen
cordsen

Reputation: 1701

It looks like your XML has some typos. Assuming your XML is like this (with <grandchild/> instead of </grandchild> under the first <child> and a closing </documentRoot>

<documentRoot>
    <parent name="data">
        <child id="1" name="alpha">
            <age>20</age>
            <grandchild/>
        </child>
        <child id="2" name="beta">
            <age>50</age>
            <grandchild id="2.1" name="beta-alpha"/>
            <grandchild id="2.2" name="beta-beta"/>
        </child>
    </parent>
</documentRoot>

This XPath will select the age of child element where <grandchild/> exists without an @id

//child[not(anotherchild/grandchild/@id)]/anotherchild/age

this will return the name for the same child

//child[not(anotherchild/grandchild/@id)]/anotherchild/@name

Upvotes: 3

Related Questions