【问题标题】:Is there a way to cleanup invalid attributes from HTML?有没有办法从 HTML 中清除无效属性?
【发布时间】:2020-07-01 07:57:15
【问题描述】:

我需要使用 javax.xml.parsers.DocumentBuilder 从 HTML 字符串创建 org.w3c.dom.Document 对象。这里有可能在该 HTML 字符串中包含无效属性及其值。那么有什么方法或 Java 工具可以只清除 HTML 中的无效属性吗?尝试了 JSOUP 清理,因为它的清理基于白名单标签和属性。但我需要只清理无效属性(根据 HTML5 标准)。

public static void main(String[] args) throws NotebookException {

        String text = "<div dir=\"ltr\"><link href=\"http://fonts.googleapis.com/css?family=Open+Sans:light:bold\" rel=\"stylesheet\" \\=\"\">";

        try(ByteArrayInputStream bais=new ByteArrayInputStream(text.getBytes()))
        {       
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(bais));
        }
        catch (Exception e) 
        {
            e.printStackTrace();  
        }
    }

在上面的代码中,带有 LINK 标记的 html 字符串具有无效的属性 '\' 及其值 '""'(空双引号)。需要清理这个解析为 Document 对象的 html。

【问题讨论】:

    标签: java html xml dom


    【解决方案1】:

    你可以使用

    String.replaceAll("[unwanted chars]","");
    

    请参阅replaceAll tutorial page 了解更多详细信息,尤其是转义字符。

    这些东西只适用于预定义的符号,为了使您的系统智能并不断更新自己遇到的每个新的无效符号,您需要编写一个方法来将这些新符号存储在适当的数据结构中,同时处理相关例外。

    【讨论】:

      【解决方案2】:

      除非您知道需要处理哪些数据,否则您无法处理任何数据。这适用于您的任务,就像适用于任何其他任务一样。如果你想处理脏数据,你需要指定你期望遇到什么样的脏数据以及你打算如何处理它。这将决定采用的方法。

      您需要做的那种处理可能可以通过现有的库来完成,例如 TagSoup 或 validator.nu。或者它可能是可以使用正则表达式来完成的。没有任务说明,我们无法知道。

      考虑一个例子。假设输入文件包含"&lt; &lt; &lt; &lt; &gt; &gt; &gt; &gt;" 你希望你的程序用它做什么?

      ...稍后

      从您的评论来看,借用 XML 术语,听起来好像 HTML 是“格式正确但无效”。这意味着您可以考虑使用 XSLT 解决方案:

      <xsl:apply-templates select="saxon:parse-html('input.bad.html')"/>
      

      ...

      <xsl:template match="a/@href | */@class | */@id | .... (:all valid attributes:)">
         <xsl:copy-of select="."/>
      </xsl:template>
      
      <xsl:template match="@* (: attributes not in the above list :)">
        <!-- no action (drop the attribute) -->
      </xsl:template>
      

      saxon:parse-html() 是 Saxon XSLT 扩展。对于其他处理器,可能还有其他方法可以将 HTML 解析为 XML DOM,并将 XML DOM 用作处理器的输入。

      【讨论】:

      • 我希望我的代码检查标签是否是 HTML4/HTML5 允许的标签,如果是则检查属性并删除该标签不支持的属性。
      猜你喜欢
      • 2022-11-06
      • 2022-08-23
      • 2016-01-06
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多