如何使用XPath获取节点的值?
获取价格高于35 的所有节点
/bookstore/book[price>35.00]
但是当我改变>对于= =等于,查询失败。 请帮忙。顺便说一下,我使用的是php,但这并不重要,因为XPath是通用的。
这是我正在使用的php代码和xml代码
$xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
<bookstore>
<book>
<title lang=\"eng\">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang=\"eng\">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>"; $xml = new SimpleXMLElement($xml);
$name = 'Shiny Red';
$nodes = $xml->xpath(sprintf('/bookstore/book[price>35.00]', $name));
if (!empty($nodes)) {
printf('At least one building named "%s" found<hr/>', $name);
echo "<textarea style=\"width: 400px; height: 300px;\">";print_r($nodes); echo "</textarea>";
} else {
printf('No building named "%s" found', $name);
}
答案 0 :(得分:2)
//bookstore/book/price[. ='35.00']
或
//bookstore/book[price='35.00']
诀窍在引号中。节点值是文本。但是,您不会将任何内容与'35 .00'匹配,但这是因为您的XML不包含具有该价格的图书。匹配'39 .95'将起作用(测试)。
$xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
<bookstore>
<book>
<title lang=\"eng\">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang=\"eng\">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>"; $xml = new SimpleXMLElement($xml);
$name = 'Shiny Red';
$nodes = $xml->xpath(sprintf('//bookstore/book/price[. = \'39.95\']', $name));
if (!empty($nodes)) {
printf('At least one building named "%s" found<hr/>', $name);
echo "<textarea style=\"width: 400px; height: 300px;\">";print_r($nodes); echo "</textarea>";
} else {
printf('No building named "%s" found', $name);
}