这是我正在使用的 XML 代码:
<inventory>
<drink>
<lemonade supplier="mother" id="1">
<title>Super Lemonade</title>
<price>$2.50</price>
<amount>20</amount>
</lemonade>
<lemonade supplier="mike" id="4">
<title>Lemonade Plus</title>
<price>$3.00</price>
<amount>20</amount>
</lemonade>
<pop supplier="store" id="2">
<title>Poppys</title>
<price>$1.50</price>
<amount>10</amount>
</pop>
</drink>
</inventory>
然后我编写了一个简单的代码来练习使用 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;
}
?>
该代码运行良好,按预期输出所有柠檬水价格值。
现在我需要一个 XPATH 来获取所有金额 = 20 的商品的标题和供应商。
我该怎么做 ?
谢谢
一般来说,您希望使用直接路径//
搜索,因为它更快:
/inventory/drink/lemonade[amount=20]/title
and
/inventory/drink/lemonade[amount=20]/@supplier
您可以将两个 XPath 查询与|
(UNION) 运算符,然后将返回四个节点。
使用 DOM 对属性进行编程访问的说明如下:
- 获取 A 元素的 href 属性 https://stackoverflow.com/questions/3820666/regular-expression-for-grabbing-the-href-attribute-of-an-a-element/3820783#3820783
您可以在以下位置找到一个很好的 XPath 教程:
- http://schlitt.info/opensource/blog/0704_xpath.html http://schlitt.info/opensource/blog/0704_xpath.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)