如何通过 XPath 在 HTML 元素中获取注释?

我想在 HTML 元素中获取注释,但显然,注释不在 DOM 元素的层次结构中。


例如,


<!-- FIRST -->

<div id="parent">

<!-- SECOND -->

    <span id="child">

<!-- THIRD -->

    </span

</div>

使用的第二个参数时$xpath->query无效。


$comments=$xpath->query('//comment()');

foreach($comments as $comment){

echo $comment->nodeValue.PHP_EOL;

}


// Query (intended) within <div id="parent">

$el = $doc->getElementById('parent');


$comments=$xpath->query('//comment()',$el);

foreach($comments as $comment){

echo $comment->nodeValue.PHP_EOL;

}


// Query (intended) within <div id="child">

$el = $doc->getElementById('child');


$comments=$xpath->query('//comment()',$el);

foreach($comments as $comment){

echo $comment->nodeValue.PHP_EOL;

}

并且所有三个循环的输出都是相同的,


 FIRST 

 SECOND 

 THIRD 

 FIRST 

 SECOND 

 THIRD 

 FIRST 

 SECOND 

 THIRD 


LEATH
浏览 129回答 1
1回答

largeQ

必须相对于给定的上下文节点选择评论。xpath 表达式中的//(descendant-or-self) 前缀选择节点中任何位置的每个注释,无论上下文如何。我建议使用.//(self, descendant-or-self) xpath 表达式进行相对搜索,以在提供的上下文中进行搜索。例如,<?php$xml = <<< XML<!-- FIRST --><div id="parent"><!-- SECOND -->&nbsp; &nbsp; <span id="child"><!-- THIRD -->&nbsp; &nbsp; </span></div>XML;$dom = new DOMDocument;$dom->loadHTML($xml);$xpath = new DOMXpath($dom);文档中的所有评论<?php$comments = $xpath->query('.//comment()', $dom);foreach($comments as $comment){&nbsp; &nbsp; echo $comment->nodeValue.PHP_EOL;}&nbsp;FIRST&nbsp;SECOND&nbsp;THIRD评论区里的所有评论div#parent<?php$el = $dom->getElementById('parent');$comments = $xpath->query('.//comment()', $el);foreach($comments as $comment){&nbsp; &nbsp; echo $comment->nodeValue.PHP_EOL;}&nbsp;SECOND&nbsp;THIRD中的所有评论span#child<?php$el = $dom->getElementById('child');$comments = $xpath->query('.//comment()', $el);foreach($comments as $comment){&nbsp; &nbsp; echo $comment->nodeValue.PHP_EOL;}&nbsp;THIRD
打开App,查看更多内容
随时随地看视频慕课网APP