【问题标题】:Preventing Jsoup.parse from removing the closing </img> tag防止 Jsoup.parse 删除结束 </img> 标记
【发布时间】:2017-04-23 18:14:34
【问题描述】:

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

【问题讨论】:

  • 能否请您发布您的Jsoup解析代码,以便我们了解它为什么要删除结束标签。
  • @SachinSarawgi,已更新

标签: java jsoup html-parsing pdf-parsing


【解决方案1】:

您的 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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多