I got an xml file that I need to work on (adding it in the end of the post). I need to retrieve the node “ActivityTime” 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>
<ActivityTime>1993-08-11 </ActivityTime>
</Document>
CodePudding user response:
First, you need to wrap your Document nodes in a single parent node, as an XML file can only have one root.
Then you can use the following XPath selector:
//Document[.//Field[Code[text()='DocumentTypeValue'] and Value[text()='1319']]]//ActivityTime
Translation: Look for any descendants of type Document
that have a descendant of type Field
which contains both a Code
child with the text 'DocumentTypeValue' and a Value
child with text '1319'. Then get the descendant of that Document
node with type ActivityTime.
The general structure of such XPath expressions is:
//ParentNode[expressions to narrow down which parent node I want]//NodeIAmLookingFor[if necessary, expression to narrow down which node I am looking for]