dean.vaughan
dean.vaughan

Reputation: 31

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/drink/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.

Upvotes: 1

Views: 177

Answers (2)

Michael Kay
Michael Kay

Reputation: 163665

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

Upvotes: 1

dogbane
dogbane

Reputation: 274888

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

Upvotes: 1

Related Questions