对于以下 XML,是否可以使用 XPath 表达式选择具有相同代码的区域项目金额在本地项目金额的 5% 以内的本地项目元素?在此示例中,将选择本地项目 4。
<?xml version="1.0" encoding="UTF-8"?>
<Inventory>
<Local>
<Item>
<Code>1</Code>
<Amount>10000</Amount>
</Item>
<Item>
<Code>2</Code>
<Amount>20000</Amount>
</Item>
<Item>
<Code>3</Code>
<Amount>30000</Amount>
</Item>
<Item>
<Code>4</Code>
<Amount>40000</Amount>
</Item>
</Local>
<Regional>
<Item>
<Code>2</Code>
<Amount>100</Amount>
</Item>
<Item>
<Code>4</Code>
<Amount>39900</Amount>
</Item>
</Regional>
</Inventory>
到目前为止,我只能使用下面的表达式选择具有相同代码的本地项目,它返回两个元素,但我似乎无法弄清楚如何将两个元素乘以 0.95,因为添加了 "/Amount * 0.95"到此表达式的末尾会导致它仅返回第一个项目的金额乘以 0.95。
/Inventory/Local/Item[Code=/Inventory/Regional/Item/Code]
最佳答案
你可以试试xquery
:
XQuery
for $x in doc("input.xml")//Local/Item
let $y:=doc("input.xml")//Regional/Item[Code=$x/Code]
where $y/Amount*0.95<=$x/Amount and $x/Amount<=$y/Amount*1.05
return $x
在 shell 中测试
$ zorba -q 'for $x in doc("input.xml")//Local/Item let $y:=doc("input.xml")//Regional/Item[Code=$x/Code] where $y/Amount*0.95<=$x/Amount and $x/Amount<=$y/Amount*1.05 return $x'
输出
<?xml version="1.0" encoding="UTF-8"?>
<Item>
<Code>4</Code>
<Amount>40000</Amount>
</Item>
关于xml - XPath 表达式根据另一个节点的值选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15421531/