防止 Jsoup.parse 删除结束 </img> 标签

Preventing Jsoup.parse from removing the closing </img> tag

我正在用 Jsoup.parse 解析一段 html。

其他一切都很好,但我应该稍后在 pdf 转换器中解析这个 html。

出于某种原因,Jsoup.parse 删除了结束标记,pdf 解析器抛出有关缺少结束 img 标记的异常。

Can't load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException; 
lineNumber: 115; columnNumber: 4; The element
type "img" must be terminated by the matching end-tag "</img>"

如何防止 Jsoup.parse 删除关闭的 img 标签?

例如这一行:

<img src="C:\path\to\image\image.png"></img>

转为:

<img src="C:\path\to\image\image.png">

同样发生在:

<img src="C:\path\to\image\image.png"/>

代码如下:

private void createPdf(File file, String content) throws IOException, DocumentException {
        OutputStream os = new FileOutputStream(file);
            content = tidyUpHTML(content);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(content);
            renderer.layout();
            renderer.createPDF(os);
        os.close();
    }

这是在上述方法中调用的 tidyUpHTML 方法:

private String tidyUpHTML(String html) {
    org.jsoup.nodes.Document doc = Jsoup.parse(html);
    doc.select("a").unwrap();
    String fixedTags = doc.toString().replace("<br>", "<br />");
    fixedTags = fixedTags.replace("<hr>", "<hr />");
    fixedTags = fixedTags.replaceAll("&nbsp;","&#160;");
    return fixedTags;
}

您的 PDF 转换器需要 xhtml(因为它需要结束 img 标签)。将 Jsoup 设置为输出到 xhtml (xml)。

org.jsoup.nodes.Document doc = Jsoup.parse(html);
document.outputSettings().syntax( Document.OutputSettings.Syntax.xml);
doc.select("a").unwrap();
String fixedTags = doc.html();