【问题标题】:xpath get first element based on multi-level conditionxpath 根据多级条件获取第一个元素
【发布时间】:2022-01-07 12:01:18
【问题描述】:

我有以下 xml。

<root>
<h>
    <seg>
        <hfield1>hA</hfield1>
        <hfield2>h1</hfield2>
    </seg>
    <seg>
        <hfield1>hB</hfield1>
        <hfield2>h2</hfield2>
    </seg>
</h>
<i>
    <iseg>
        <ifield1>i1</ifield1>
    </iseg>
    <iseg>
        <ifield1>i2</ifield1>
    </iseg>
</i>
<i>
    <iseg>
        <ifield1>i3</ifield1>
    </iseg>
    <iseg>
        <ifield1>i4</ifield1>
    </iseg>
</i>

如果 hfield2 = 'h2' 并且至少有一个 ifield1 = 'i2',我需要提取 hfiel1 的值。 我正在用这个表达式尝试 xpath 1.0。结果是“hB”,但它不起作用。

//seg/hfield1/text()[..//hfield2/text() = 'h2' and //ifield1 = 'i2'][1]

我该怎么办?

BR

【问题讨论】:

    标签: xpath conditional-statements nodes


    【解决方案1】:

    试试这个 XPath-1.0 表达式:

    //seg/hfield1[../hfield2 = 'h2' and //ifield1 = 'i2']
    

    【讨论】:

      【解决方案2】:

      除了 zx485 的解决方案,您还可以使用以下 XPath 1:0 表达式:

      //seg/hfield2[text() = 'h2' and //ifield1 = 'i2']/preceding-sibling::hfield1
      

      【讨论】:

        【解决方案3】:

        如果您的 xml-tree 变得更大,我建议使用更明确的 XPath,即:

        /root[i/iseg/ifield1='i2']/h/seg[hfield2='h2']/hfield1/text()
        

        【讨论】:

          猜你喜欢
          • 2015-12-03
          • 2022-08-17
          • 2011-08-03
          • 1970-01-01
          • 2021-08-20
          • 2019-07-16
          • 2015-07-10
          • 1970-01-01
          • 2020-07-20
          相关资源
          最近更新 更多