douan0729
2018-12-23 22:25
浏览 63
已采纳

在Xpath查询中排除链接

Thinking this should be relatively easy but I'm having trouble finding the right syntax apparently.

Here's what I'm working with minified

$dom = new DOMDocument();
libxml_use_internal_errors(true);

$dom->LoadHTML('<div class="intro"><div class="special"><span class="point"><span class="us">US </span><span>20.00</span></span> per <p class="original"><span class="us">US</span> 7.50 <a href="test.html">Link</a></p></div></div>');

$xp = new DOMXPath($dom);

$path = $xp->query('//div[@class="intro"]');

foreach($path as $p)
{
echo '<pre>';
print_r($p);
echo '</pre>';
}

This brings back

[nodeValue] => US 20.00 per US 7.50 Link

What I'm trying to do is exclude any a or href link elements in the query so the nodeValue simply brings back

[nodeValue] => US 20.00 per US 7.50

Here's a few of what I've tried to achieve this in my xpath query to achieve this:

$path = $xp->query('//div[@class="intro" and not(@href)]');
$path = $xp->query('//div[@class="intro" and not(a)]');
$path = $xp->query('//div[@class="intro"][not(a)]');
$path = $xp->query('//div[@class="intro"][not(@href)]');
$path = $xp->query('//div[@class="intro"][not(self::a)]');

None of these have worked.

What is needed for my query to exclude any link elements in the result?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doutang7661 2018-12-23 22:43
    已采纳

    You can exclude link text nodes from results with

    //div[@class="intro"]//text()[not(parent::a)]
    

    or

    string-join(//div[@class="intro"]//text()[not(parent::a)], " ")
    
    点赞 打赏 评论

相关推荐 更多相似问题