techq
techq

Reputation: 85

xpath expression to read value based on value of sibling

I've below xml and would like to read the value of 'Value' tag whose Name matches 'test2'. I'm using the below xpath , but did not work. Can someone help.

/*[ local-name()='OutputData']/*[ local-name()='OutputDataItem']/*[ local-name()='Name'][normalize-space(.) = 'test2']//*[local-name()='Value']/text()

             <get:OutputData>
              <get:OutputDataItem>
                 <get:Name>test1</get:Name>
                 <get:Value/>
              </get:OutputDataItem>
              <get:OutputDataItem>
                 <get:Name>test2</get:Name>
                 <get:Value>B5B4</get:Value>
              </get:OutputDataItem>
              <get:OutputDataItem>
                 <get:Name>test3</get:Name>
                 <get:Value/>
              </get:OutputDataItem>
              <get:OutputDataItem>
                 <get:Name>OP_VCscEncrptCd_VAR</get:Name>
                 <get:Value/>
              </get:OutputDataItem>                  
           </get:OutputData>

Thanks

Upvotes: 2

Views: 108

Answers (2)

eLRuLL
eLRuLL

Reputation: 18799

This should work I think:

//*[local-name()="get:Name" and text()="test2"]/following-sibling::*[local-name()="get:Value"]/text()

Upvotes: 2

Mads Hansen
Mads Hansen

Reputation: 66714

You were close, but because the get:name and get:value are siblings, you need to adjust your XPath a little.

Your XPath was attempting to address get:value elements that were descendants of get:name, rather than as siblings. Move the criteria that is filtering the get:name into a predicate, then step down into the get:value:

/*[ local-name()='OutputData']/*[ local-name()='OutputDataItem']
  [*[ local-name()='Name'][normalize-space(.) = 'test2']]/*[local-name()='Value']/text()

You could also combine the criteria of the predicate filter on the get:name and use an and:

/*[ local-name()='OutputData']/*[ local-name()='OutputDataItem']
  [*[ local-name()='Name' and normalize-space(.) = 'test2']]/*[local-name()='Value']/text()

Upvotes: 2

Related Questions