开发者

XPath basic query

im just trying to learn xpath when i have a small question. let's say i have this XML.

<inventory>
    <drink>
        <lemonade supplier="mother" id="1">
            <price>$2.50</price>
            <amount>20</amount>
        </lemonade>
        <pop supplier="store" id="2">
            <price>$1.50</price>
            <amount>10</amount>
        </pop>
    </drink>
</inventory>

$result = new SimpleXMLElement($string);

$res = $result->xpath("/inventory/dri开发者_如何学编程nk/lemonade[@supplier='mother' and amount > 2]");

as you can see the above query checks the supplier and amount within the lemonade node, how do I then check the pop node within the same expression, basically I don't know how to go back a node within the same expression.


What you haven't said is what you want your XPath expression to return. Is it a drink, a supplier, a price?

Suppose you want to return a price. Then the basic path to the price is

/inventory/drink/pop/price

Then you can add conditions (filter predicates) to any step along this path

/inventory/drink[lemonade/@supplier='mother']/pop[@supplier='store']/price


The easiest way is to use ../pop to go up to the pop node:

/inventory/drink/lemonade[@supplier='mother' and amount > 2]/../pop

Alternatively:

/inventory/drink[lemonade[@supplier='mother' and amount > 2]]/pop
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜