【问题标题】:Using XPATH to get the node location to retrieve another value from the same tree but not the same node使用 XPATH 获取节点位置以从同一棵树但不是同一节点检索另一个值
【发布时间】:2021-12-31 19:20:30
【问题描述】:

我有一个需要处理的 xml 文件(在帖子末尾添加)。只有当我找到节点“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>

【问题讨论】:

    标签: xml xpath


    【解决方案1】:

    首先,您需要将 Document 节点包装在一个父节点中,因为 XML 文件只能有一个根。

    然后您可以使用以下 XPath 选择器:

    //Document[.//Field[Code[text()='DocumentTypeValue'] and Value[text()='1319']]]//ActivityTime
    

    翻译:查找具有Field 类型的后代的Document 类型的任何后代,其中包含带有文本“DocumentTypeValue”的Code 子代和带有文本“1319”的Value 子代。然后获取 Document 类型为 ActivityTime 的节点的后代。

    此类 XPath 表达式的一般结构是:

    //ParentNode[expressions to narrow down which parent node I want]//NodeIAmLookingFor[if necessary, expression to narrow down which node I am looking for]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      相关资源
      最近更新 更多