使用 PHP 进行 Xpath 查询(取两个值) [英] Xpath query with PHP (take two values)
问题描述
这是我正在使用的 XML 代码:
Here's the XML code i'm working with:
<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:
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.
现在我需要一个 XPATH 来获取数量 = 20 的所有项目的 TITLE 和 SUPPLIER.
Now I need a XPATH to get me the TITLE and SUPPLIER of all items with amount = 20.
我该怎么做?
谢谢
推荐答案
使用:
/*/*/*[amount = 20]/@supplier | /*/*/*[amount = 20]/title
这个选择:
作为 XML 文档顶部元素的孙子元素的任何元素的任何
supplier
属性(与/inventory/drink/lemonade
相同),但我喜欢编写较短的 XPath 表达式),其amount
子项具有可转换为数字 20 的字符串值.
Any
supplier
attribute of any element that is a grand-child of the top element of the XML document (the same as/inventory/drink/lemonade
, but I like to write shorter XPath expressions), whoseamount
child has a string value that is castable to the number 20.
作为 XML 文档顶部元素的孙子元素的任何元素的任何 title
子元素(与 /inventory/drink/lemonade
相同),但我喜欢编写较短的 XPath 表达式),其 amount
子项具有可转换为数字 20 的字符串值.
Any title
child of any element that is a grand-child of the top element of the XML document (the same as /inventory/drink/lemonade
, but I like to write shorter XPath expressions), whose amount
child has a string value that is castable to the number 20.
基于 XSLT 的验证:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="node()|@*">
<xsl:for-each select=
"/*/*/*[amount = 20]/@supplier
|
/*/*/*[amount = 20]/title">
<xsl:value-of select="."/>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的 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 表达式并在单独的行上复制所选模式的值:
mother
Super Lemonade
mike
Lemonade Plus
请注意:
使用诸如 XPath Visualizer -- 成千上万的人使用它以有趣的方式学习 XPath.
Your learning of XPath can greatly be helped by using a tool such as the XPath Visualizer -- used by many thousands of people to learn XPath the fun way.
这篇关于使用 PHP 进行 Xpath 查询(取两个值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!