开发者

How do I get the value of a node with XPath?

How do I get the value of a nod开发者_JAVA技巧e with XPath?

Get all nodes which have a price above 35

/bookstore/book[price>35.00]

But when I change the > to an = for equals, the query fails. Please help. By the way I'm using php, but that shouldn't matter as XPath is universal.

Here's the php code and xml code I was using

$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);
    }    


//bookstore/book/price[. ='35.00']

or

//bookstore/book[price='35.00']

The trick is in the quotes. Node values are text. You won't match anything with '35.00' however, but that is because your XML doesn't contain books with that price. Matching '39.95' will work (tested).

$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);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜