使用 XPATH 获取节点位置以从同一棵树但不是同一节点检索另一个值
Using XPATH to get the node location to retrieve another value from the same tree but not the same node
我有一个 xml 文件需要处理(将其添加到 post 的末尾)。只有当我找到节点“DocumentTypeValue”= 1319 时,我才需要检索节点“ActivityTime”。有没有办法只在一个 XPATH 中查看它?或者我应该寻找 DocumentTypeValue ==1319 并获取当前位置,以便我可以使用刚刚检索到的位置创建 XPATH?谢谢大家的帮助!
文件是-
<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>
首先,您需要将文档节点包装在单个 parent 节点中,因为 XML 文件只能有一个根。
那么你可以使用下面的 XPath 选择器:
//Document[.//Field[Code[text()='DocumentTypeValue'] and Value[text()='1319']]]//ActivityTime
翻译:查找类型 Document
的任何后代,其后代类型 Field
包含 Code
child 和文本 'DocumentTypeValue' 和带有文本“1319”的 Value
child。然后获取类型为 ActivityTime 的 Document
节点的后代。
此类 XPath 表达式的一般结构是:
//ParentNode[expressions to narrow down which parent node I want]//NodeIAmLookingFor[if necessary, expression to narrow down which node I am looking for]
我有一个 xml 文件需要处理(将其添加到 post 的末尾)。只有当我找到节点“DocumentTypeValue”= 1319 时,我才需要检索节点“ActivityTime”。有没有办法只在一个 XPATH 中查看它?或者我应该寻找 DocumentTypeValue ==1319 并获取当前位置,以便我可以使用刚刚检索到的位置创建 XPATH?谢谢大家的帮助!
文件是-
<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>
首先,您需要将文档节点包装在单个 parent 节点中,因为 XML 文件只能有一个根。
那么你可以使用下面的 XPath 选择器:
//Document[.//Field[Code[text()='DocumentTypeValue'] and Value[text()='1319']]]//ActivityTime
翻译:查找类型 Document
的任何后代,其后代类型 Field
包含 Code
child 和文本 'DocumentTypeValue' 和带有文本“1319”的 Value
child。然后获取类型为 ActivityTime 的 Document
节点的后代。
此类 XPath 表达式的一般结构是:
//ParentNode[expressions to narrow down which parent node I want]//NodeIAmLookingFor[if necessary, expression to narrow down which node I am looking for]