18

Here's the XML code I'm working with:

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

Then I wrote a simple code to practice working with XPath:

<?php
    $xmldoc = new DOMDocument();
    $xmldoc->load('sample.xml');

    $xpathvar = new Domxpath($xmldoc);

    $queryResult = $xpathvar->query('//lemonade/price');
    foreach($queryResult as $result) {
        echo $result->textContent;
    }
?>

That code is working well, outputting all the lemonade price values as expected. Now when i change the query string to select only the elements with an attribute set to a certain value, like

//lemonade[supplier="mother"]/price

or

//lemonade[id="1"]/price

it won't work, no output at all. What am i doing wrong?

Manoj Sharma
  • 1,467
  • 2
  • 13
  • 20
liewl
  • 4,021
  • 13
  • 46
  • 65

3 Answers3

34

Try this:

//lemonade[@id="1"]/price

or

//lemonade[@supplier="mother"]/price

Without the "@" it looks for child elements with that name instead of attributes.

bobwienholt
  • 17,420
  • 3
  • 40
  • 48
8

This is only tangentially related, but when you use XPath on a document for which you know the structure, don't use "//some-element-name". It's very nice for a quick example, but when you hit a huge xml file with that query, particularly if it is followed by something complex, you will quickly run into performance issues.

inventory/drink/lemonade[@supplier="mother"]/price

Tirno
  • 1,568
  • 2
  • 16
  • 21
7

you have to use the @ sign to indicate attribute within the predicate like so: //lemonade[@supplier="mother"]/price, that's all.

Kris
  • 40,604
  • 9
  • 72
  • 101