user2123852
user2123852

Reputation: 59

XPATH for sibling node based on condition of previous child

I have following xml and would like to fetch the "cc" value of "type" ID where a "type" of student exist. I want XPATH to get the value 345.

I have tried this but not getting any value.//a/cc[type="bond"]/following-sibling::cc[type="id"]/value/text()

<?xml version="1.0" encoding="UTF-8"?>

<root> 
  <a> 
    <bb>abc</bb>  
    <cc> 
      <type>id</type>  
      <value>345</value> 
    </cc>  
    <cc> 
      <type>student</type>  
      <value>567</value> 
    </cc>  
    <dd>ddd</dd> 
  </a>  
  <a> 
    <bb>zz</bb>  
    <cc> 
      <type>id</type>  
      <value>999</value> 
    </cc>  
    <cc> 
      <type>employee</type>  
      <value>890</value> 
    </cc>  
    <dd>2</dd> 
  </a> 
</root>

Upvotes: 1

Views: 1089

Answers (2)

Sergio Tx
Sergio Tx

Reputation: 3868

Try this:

//a[cc[type="student"]]/cc[type="id"]/value/text()

(Tested in https://codebeautify.org/Xpath-Tester)

Upvotes: 0

choroba
choroba

Reputation: 242373

Replace following-sibling by preceding-sibling (and bond by student).

//a/cc[type="student"]/preceding-sibling::cc[type="id"]/value/text()

(Tested in xsh).

Upvotes: 1

Related Questions