使用PHP进行Xpath查询(取两个值)
发布时间:2020-12-13 17:18:04 所属栏目:PHP教程 来源:网络整理
导读:这是我正在使用的 XML代码: inventory drink lemonade supplier="mother" id="1" titleSuper Lemonade/title price$2.50/price amount20/amount /lemonade lemonade supplier="mike" id="4" titleLemonade Plus/title price$3.00/price amount20/amount /le
这是我正在使用的
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的所有项目的TITLE和SUPPLIER. 我该怎么做 ? 谢谢 解决方法
使用:
/*/*/*[amount = 20]/@supplier | /*/*/*[amount = 20]/title 这选择: >任何元素的任何供应商属性,它是XML文档顶级元素的子元素(与/ inventory / drink / lemonade相同,但我喜欢编写更短的XPath表达式),其子元素值具有字符串值可以施放到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 请注意: 通过使用诸如the XPath Visualizer之类的工具可以极大地帮助您学习XPath – 成千上万的人使用它来学习XPath的有趣方式. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |