使用xPath的多个过滤器

时间:2013-05-22 08:29:07

标签: php xml xpath

我有以下格式的XML

<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>

我正在努力获得以下内容:

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

这意味着在上面,结果将是Item 2

到目前为止我已经关注:

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

然后我可以循环访问并获取XML,如下所示:

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

问题是xpath过滤器的第二部分,价格高于15

我试过了:

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

但这给了我一个错误:

Warning: SimpleXMLElement::xpath(): Invalid expression

我可以将两个搜索结合到一个过滤器中吗?

由于

已更新

$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
}

1 个答案:

答案 0 :(得分:1)

获得所需输出Item 2的完整XPATH是:

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