我想将一些 Html 字符串解析为 org.w3c.dom.Document,我使用这种方法:
public static Document stringToDocument(String input){
try {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(input));
Document doc = db.parse(is);
return doc;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
这在大多数 html 上都可以正常工作,除了 html 字符串有“colgroup”和“col”标签(如下所示)
<html dir="rtl"><head><meta charset="utf-8"/></head>
<body>
<table>
<colgroup>
<col width="29">
<col style="width:54pt" span="4" width="72">
<col width="4">
</colgroup>
<tbody>
<tr>
<td>test</td>
<td>105</td>
<td>110</td>
</tr>
<tr>
<td>456</td>
<td>456</td>
<td>786</td>
</tr>
</tbody>
</table>
</body>
</html>
方法抛出的异常是:
org.xml.sax.SAXParseException; lineNumber: 8; columnNumber: 6; The end-tag for element type "col" must end with a '>' delimiter.
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
根据w3schools, col 标签语法是正确的,我不知道如何解决这个问题。