Using XPATH to get the node location to retrieve another value from the same tree

Viewed 55

I got an xml file that I need to work on (adding it in the end of the post). I need the retrieve the node “DocIDAutoNumerator” only when I find the node “DocumentTypeValue” = 1319. Is there a way to look it in just one XPATH? or should I look for DocumentTypeValue ==1319 and get the current position so I can make a XPATH using the location I just retrieved? Thank you all for your help!

the file is -

    <Document>
       <Labels>
          <Label>
             <Fields>
                <Field>
                   <Code>DocumentTypeValue</Code>
                   <Value>4008</Value>
                </Field>
                <Field>
                   <Code>DocIDAutoNumerator</Code>
                   <Value>123121</Value>
                </Field>
             </Fields>
          </Label>
       </Labels>
      <ActivityTime>2021-08-11 </ActivityTime>
    </Document>

    <Document>
       <Labels>
          <Label>
             <Fields>
                <Field>
                   <Code>DocumentTypeValue</Code>
                   <Value>1319</Value>
                </Field>
                <Field>
                   <Code>DocIDAutoNumerator</Code>
                   <Value>21321</Value>
                </Field>
             </Fields>
          </Label>
       </Labels>
    </Document>
3 Answers

To get the <Field> node that contains the <Code> element with the value "DocIDAutoNumerator" having a Field/Code sibling with the value "1319" you can use the following XPath-1.0 expression:

//Field[Code='DocIDAutoNumerator' and ../Field[Value='1319']]

This returns the <Field> element with the required properties.
To get its Value, append the String /Value to the expression.
And to retrieve its Code element, append the String /Code.

This XPath,

//Fields[Field[Code="DocumentTypeValue"][Value="1319"]]
 /Field[Code="DocIDAutoNumerator"]/Value

selects Value element of a Field which

  • has a "DocIDAutoNumerator" Code, and
  • is in the same Fields element with a Field that
    • has a "DocumentTypeValue" Code and has a "1319" Value.

This should work:

//Document[.//Code/text() = "DocumentTypeValue"/following-sibling::Value/text() = "1319"]////Code/text() = "DocIDAutoNumerator"/following-sibling::Value/text()
Related