duanhuayong6687 2013-11-01 15:03
浏览 81
已采纳

xpath-> query的递归上下文节点

Basically what I'm trying to achieve is replacing the content of the src-attributes of a bunch of img-nodes by the content of the corresponding data-src-nodes in a page like the following one.

<html>
   <body>
      <div id="a">
         <img src="" data-src="myValue" />
         <img src="" data-src="myValue2" />
      </div>
      <img src="" data-src="myValue" />
   </body>
</html>

I want to do this by finding a common base node (in this case the img nodes in the div with id a) and based on that node

  • the node containing the value to copy and#
  • the node retrieving the value

Script

<?PHP
$html = '<html><body><div id="a"><img src="" data-src="myValue"/><img src="" data-src="myValue2"/></div><img src="" data-src="myValue"/></body></html>';
$doc = new DOMDocument();
@$doc->loadHTML($html);

$basenode = false;
$xpath = new DOMXPath($doc);
$entries = $xpath->query('(//div[@id="a"])');

if ($entries->length > 0) $basenode = $entries->item(0);
if ($basenode) {
    $img = $xpath->query('//img', $basenode);
    foreach ($img as $curImg) {
        $from = $xpath->query('//@data-src', $curImg);
        $to = $xpath->query('//@src', $curImg);
        $to->item(0)->value = $from->item(0)->value;
    }
    echo $doc->saveXML();
}
?>

Expected output

<html>
   <body>
      <div id="a">
         <img src="myValue" data-src="myValue" />
         <img src="myValue2" data-src="myValue2" />
      </div>
      <img src="" data-src="myValue" />
   </body>
</html>

Actual output

<html>
   <body>
      <div id="a">
         <img src="myValue" data-src="myValue" />
         <img src="" data-src="myValue2" />
      </div>
      <img src="" data-src="myValue" />
   </body>
</html>

So, the line

$from = $xpath->query('//@data-src', $curImg);

seems to actually base its search on the root node and not the img-node selected before. How can I solve this?

(I know that a possible workaround would be to omit selecting the img-nodes explicitly and doing something like from='//div[@id="a"]/img/@data-src' and to='//div[@id="a"]/img/@src' but I'm a bit concerned, that I might end up copying values between attributes of different nodes)

  • 写回答

1条回答 默认 最新

  • dqtiober37522 2013-11-01 15:15
    关注

    / at the beginning specifies an absolute location path (i.e, from the document root). Instead, you want to use a relative one (relative to the context node).

    For example; .//@data-src, or descendant::img/@data-src, and so on.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题