使用XPath从嵌套XML中获取值

时间:2016-07-20 18:28:34

标签: xml xpath

我想使用XPath表达式从下面的XML中获取元素数量及其值。

<donor>
    <beneficiaries>
        <beneficiary>
            <balance>10</balance>
            <additionaData>
                <name>age</name>
                <value>40</value>
            </additionaData>
            <additionaData>
                <name>amount</name>
                <value>1000</value>
            </additionaData>
        </beneficiary>
        <beneficiary>
            <balance>10</balance>
            <additionaData>
                <name>age</name>
                <value>50</value>
            </additionaData>
            <additionaData>
                <name>amount</name>
                <value>4000</value>
            </additionaData>
        </beneficiary>
    </beneficiaries>
</donor>

我可以获取受益人元素的NodeList,但无法获取标记namevalue的内容。

更新

我想首先检查<name>中的标记<additionalData>是否为金额,如果是,请为所有<value>获取<beneficiary>的内容。

2 个答案:

答案 0 :(得分:1)

这个XPath,

value

将选择与“金额”name元素相关联的两个<value>1000</value> <value>4000</value> 元素:

/donor/beneficiaries/beneficiary[additionaData[name='age']/value = 50]
                    /additionaData[name='amount']/value

这个XPath,

value

将仅选择50岁beneficiary的“金额”<value>4000</value> 元素:

<name>

<强>更新

  

我实际上想先检查标签<additionalData>是否在   如果是,则<beneficiary>为获取for的内容   所有/donor/beneficiaries/beneficiary[additionaData/name='amount']

这个XPath,

beneficiary

将选择additionaData/name等于"amount"的所有<beneficiary> <balance>10</balance> <additionaData> <name>age</name> <value>40</value> </additionaData> <additionaData> <name>amount</name> <value>1000</value> </additionaData> </beneficiary> <beneficiary> <balance>10</balance> <additionaData> <name>age</name> <value>50</value> </additionaData> <additionaData> <name>amount</name> <value>4000</value> </additionaData> </beneficiary> 个元素:

BigDecimal(1) / BigDecimal(3) * BigDecimal(3)
# => #<BigDecimal:19289d8,'0.9999999999 99999999E0',18(36)>

答案 1 :(得分:0)

以下xpath将给出值

//donor/beneficiaries/beneficiary/additionaData/*[name()='name'][.='amount']/following-sibling::*[name()='value']

Element='<value>1000</value>'
Element='<value>4000</value>'

如果您想获得age个节点

通过将amount替换为age

来修改上述xpath