在文档片段中查找注释或文本节点 [英] Find comment or text nodes in a document fragment

查看:41
本文介绍了在文档片段中查找注释或文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须清理 Nokogiri::HTML::DocumentFragment 文档(删除仅包含空格的注释节点和文本节点).举个例子:

I have to clean up a Nokogiri::HTML::DocumentFragment document (remove comment nodes and text nodes which contain whitespace only). Here's an example:

html = "<p>paragraph</p><!-- comment --><p>paragraph</p>   <p>paragraph</p>"
doc = Nokogiri::HTML::DocumentFragment.parse html

文档片段如您所愿:

#(DocumentFragment:0x3fc65f9f5870 {
  name = "#document-fragment",
  children = [
    #(Element:0x3fc65f9f5064 { name = "p", children = [ #(Text "paragraph")] }),
    #(Comment " comment "),
    #(Element:0x3fc65f9f4f60 { name = "p", children = [ #(Text "paragraph")] }),
    #(Text "   "),
    #(Element:0x3fc65f9f4e48 { name = "p", children = [ #(Text "paragraph")] })
  ]
})

如何在此文档片段中找到所有注释或所有文本节点?

How can I find all comment or all text nodes in this document fragment?

以下不起作用,因为它不是一个完整的文档,而是一个文档片段:

The following don't work because it's not a full document but a document fragment:

doc.search('//text()')
doc.search('//comment()')

推荐答案

想通了:

doc.search('.//text()')
doc.search('.//comment()')

这篇关于在文档片段中查找注释或文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆