【问题标题】:How to remove empty text elements during cleaning of the document?如何在清理文档期间删除空文本元素?
【发布时间】:2014-08-20 18:04:53
【问题描述】:

我的代码正在使用 jsoup 清洁器从文档中删除不需要的元素。我注意到在清理操作之后仍然存在许多空文本节点。由于它们没有子节点,因此应该可以删除它们。

想知道是否有人已经为此实施了解决方案......

文件输出到字符串如下:

            • 文字:
              • 文本:移动应用程序
          • 文字:
            • 文本:金融产品
            • a:另一个链接
              • 文本:xyz 视觉数据
          • 文字:
        • 文字:
        • 文字:
        • 文字:
        • 文字:
        • 文字:

【问题讨论】:

标签: java html-parsing jsoup


【解决方案1】:

删除空标签可能会很棘手,因为有些标签总是空的(例如<br/><img/>),有些标签即使是空的也会影响文档的布局(例如<p></p>)。更糟糕的是,某些 CSS 配置可能导致几乎任何类型的标签影响文档布局(例如字体图标)。

如果您可以决定您愿意删除哪些元素,那么以下方法应该有效:

// Names of the elements to remove if empty
Set<String> removable = ....

// Parse the html into a jsoup document
Document source = Jsoup.parse(myHtml);

// Clean the html according to a whitelist
Document cleaned = new Cleaner(whitelist).clean(source);

// For each element in the cleaned document
for(Element el: cleaned.getAllElements()) {

   if(el.children().isEmpty() && !el.hasText()) {
       // Element is empty, check if should be removed
       if(removable.contains(el.tagName())) el.remove();
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    相关资源
    最近更新 更多