gpt4 book ai didi

java - 防止 Jsoup.parse 移除结束的 标签

转载 作者:搜寻专家 更新时间:2023-11-01 01:49:54 27 4
gpt4 key购买 nike

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

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

关于java - 防止 Jsoup.parse 移除结束的 </img> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41040562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com