使用xpath过滤元素并选择一个作为第一个(两个条件)

时间:2014-11-26 12:41:09

标签: xml xpath

使用一个属性的特定值过滤元素,然后根据另一个属性的值将其中一个作为第一个的最佳方法是什么。

<users>
<user id="1">
    <accounts>
        <account type="100" number="100456400100"/>
        <account type="110" number="100456400110"/>
        <account type="120" selected="1" number="100456400120"/>
        <account type="130" number="100456400130"/>
        <account type="140" number="100456400140"/>
        <account type="150" number="100456400150"/>
    </accounts>
</user>
<user id="2">
    <accounts>
        <account type="100" number="200456400100"/>
        <account type="110" number="200456400110"/>
        <account type="120" number="200456400120"/>
        <account type="130" number="200456400130"/>
        <account type="140" number="200456400140"/>
        <account type="150" selected="1" number="200456400150"/>
    </accounts>
</user>

我想扩展这个xpath

users/user/accounts/account[@type='100' or @type='120' or @type='130' or @type='150']

仅选择类型为100,120,130或150的帐户。(实际上,帐户类型非常多,因此这比!=100 and !=140 ....更有效。并将具有属性selected='1'的帐户作为第一个帐户。

有没有办法用一个xpath做到这一点?

1 个答案:

答案 0 :(得分:0)

Xpath不提供sort功能,因此您需要使用一些后期处理来执行此操作(例如xslt)。

在你的例子中,为了正确得到你想要的东西,你需要使用这个Xpath

//users/user/accounts//account[@type='100' or @type='120' or @type='130' or @type='150']

否则,如果您在/之前只保留一个account,那么您将只获得第一个帐户节点。