sipher_z
sipher_z

Reputation: 1251

Multiple filters using xPath

I have some XML in the following format

<root>
 <item>
   <created>2013-05-21</created>
   <name>Item 1</name>
     <attributes>
       <stock>
         <amount>1</amount>
       </stock>
       <price>10</price>
     </attributes>
  </item>
  <item>
   <created>2013-05-21</created>
   <name>Item 2</name>
     <attributes>
       <stock>
         <amount>1</amount>
       </stock>
       <price>20</price>
     </attributes>
  </item>
  <item>
   <created>2013-05-21</created>
   <name>Item 3</name>
     <attributes>
       <stock>
         <amount>2</amount>
       </stock>
       <price>10</price>
     </attributes>
  </item>
</root>

I'm trying to get the following:

1 - Get all items that have a stock amount that is 1

2 - Get all of the filtered items that have a price greater than or equal to 15

This means in the above, the result would be Item 2

I have following so far:

$xml = new SimpleXMLElement($xmlString);
$xmlReturn = $xml->xpath("item[attributes/stock[contains(amount,'1')]]");

I can then loop through and get the XML as follows:

foreach($xmlReturn as $node){
  echo $node->asXml();
}

The problem is the second part of the xpath filter, getting the prices greater than 15.

I've tried:

$test = $xml->xpath("item[attributes/[price>15]]");

But that gives me an error:

Warning: SimpleXMLElement::xpath(): Invalid expression

Can I combine the two searches into a single filter?

Thanks

UPDATED

$data = 'XML DATA HERE';
$xml = new SimpleXMLElement($data);
$xpath = $xml->xpath("//item[attributes[stock/amount='1'][price >= 15]]");

foreach($xpath as $node)
{
   echo $node->xpath('name');
   // this throws a Notice: Array to string conversion error
}

Upvotes: 0

Views: 1589

Answers (1)

Navin Rawat
Navin Rawat

Reputation: 3138

Your complete XPATH to get desired output Item 2 is:

//item[attributes[stock/amount='1'][price >= 15]]

Upvotes: 1

Related Questions