【发布时间】: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。
【问题讨论】: