duagfgfn1981 2011-07-18 14:20
浏览 34
已采纳

如何使用XPath获取节点的值?

How do I get the value of a node 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);
    }    
  • 写回答

1条回答 默认 最新

  • douqiao6563 2011-08-02 21:53
    关注
    //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);
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数