使用XPath计算折扣

时间:2015-04-27 09:25:07

标签: xml xpath

我有这样的XML结构:

<?xml version="1.0"?>
<catalog>

   <book id="bk101">
      <title>XML Developer's Guide</title>
      <price>44.95</price>
      <sale-price>4.90</sale-price>
   </book>

   <book id="bk102">
      <title>Midnight Rain</title>
      <price>5.95</price>
      <sale-price>4.90</sale-price>
   </book>

</catalog>

我想从正常价格中选择销售价格折扣超过30%的节点。我怎么能用XPath做到这一点?

2 个答案:

答案 0 :(得分:1)

另一种看待它的方法是,您需要sale-price小于price的70%的图书。

在Xpath中:

sale-price div price < 0.7

将此作为book元素节点的条件

/catalog/book[sale-price div price < 0.7]

PHP示例:

$xml = <<<'XML'
<?xml version="1.0"?>
<catalog>

   <book id="bk101">
      <title>XML Developer's Guide</title>
      <price>44.95</price>
      <sale-price>4.90</sale-price>
   </book>

   <book id="bk102">
      <title>Midnight Rain</title>
      <price>5.95</price>
      <sale-price>4.90</sale-price>
   </book>

</catalog>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);

$expression = '/catalog/book[
  sale-price div price < 0.7
]';

foreach ($xpath->evaluate($expression) as $node) {
  echo $dom->saveXml($node);
}

输出:

<book id="bk101">
  <title>XML Developer's Guide</title>
  <price>44.95</price>
  <sale-price>4.90</sale-price>
</book>

答案 1 :(得分:1)

您可以尝试这种方式:

//book[(price - sale-price) div price > 0.3]

在xpath之上返回所有<book>节点的销售价格与正常价格相比折扣超过30%。

输出:

<book id="bk101">
  <title>XML Developer's Guide</title>
  <price>44.95</price>
  <sale-price>4.90</sale-price>
</book>