繁体   English   中英

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

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

我正在使用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;
}

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

请参阅使用Jsoup 1.8.1将HTML转换为XHTML是否可行?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM