防止Jsoup.parse删除结束标记

时间:2016-12-08 13:23:16

标签: java jsoup html-parsing pdf-parsing

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

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

由于某种原因,Jsoup.parse删除了结束标记,而pdf-parser抛出了关于缺少关闭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;
}

1 个答案:

答案 0 :(得分:7)

您的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();

请参阅Is it possible to convert HTML into XHTML with Jsoup 1.8.1?

相关问题