XPath谓词绝对vs相对后代测试?

时间:2018-04-09 00:15:41

标签: xml xpath

我想查询XML以检索每个ElementICareAbout,当它有两个ElementICareAbout2个孩子时,他们自己拥有AttributeICareAbout; AttributeICareAbout的值无关紧要。

我在下面的XPath查询对我来说似乎是正确的,但它会返回包含ElementICareAbout ElementICareAbout2的{​​{1}}的每个AttributeICareAbout

的XPath:

//ElementICareAbout[@AttributeICareAbout='ValueICareAbout']
                   [count(//ElementICareAbout2[@AttributeICareAbout2]) > 1]

XML:

<RootElement>
    <ArbitraryElement>
        <ArbitraryElement2>
            <!-- DO WANT THE BELOW ELEMENT, CONTAINS TWO ElementICareAbout2 
                 CHILDREN WITH ArbitraryAttribute -->
            <ElementICareAbout AttributeICareAbout="ValueICareAbout">
                <ArbitraryElement4>
                    <ElementICareAbout2 AttributeICareAbout2="ArbitraryValue"/>
                </ArbitraryElement4>                
                <ArbitraryElement5>
                    <ArbitraryElement6>
                        <ElementICareAbout2 AttributeICareAbout2="ArbitraryValue"/>
                    </ArbitraryElement6>
                </ArbitraryElement5>
            </ElementICareAbout>
            <!-- DON'T WANT THE BELOW ELEMENT, LACKING TWO ElementICareAbout2
                 CHILDREN WITH ArbitraryAttribute -->
            <ElementICareAbout AttributeICareAbout="ValueICareAbout">
                <ArbitraryElement4>
                    <ElementICareAbout2 AttributeICareAbout2="ArbitraryValue"/>
                </ArbitraryElement4>                
                <ArbitraryElement5>
                    <ArbitraryElement6>
                        <ElementICareAbout2 ArbitraryAttribute="ArbitraryValue"/>
                    </ArbitraryElement6>
                </ArbitraryElement5>
            </ElementICareAbout>
        </ArbitraryElement2>
        <ArbitraryElement3>
        </ArbitraryElement3>
    </ArbitraryElement>
</RootElement>

1 个答案:

答案 0 :(得分:1)

只需使谓词涉及ElementICareAbout2 relative(.//)而不是绝对(//):

//ElementICareAbout[@AttributeICareAbout='ValueICareAbout']
                   [count(.//ElementICareAbout2[@AttributeICareAbout2]) > 1]