我正在使用 JSoup 动态设置 <base/>
的 href 属性HTML 文档中的元素。除了关闭 </base>
之外,这按预期工作。修改后的 HTML 中省略了标签。
有没有办法让 JSOUP 返回有效的 XHTML?
输入:
<html><head><base href="xyz"/></head><body></body></html>
输出:
<html>
<head>
<base href="https://myhost:8080/myapp/"> <-- missing closing tag
</head>
<body></body>
</html>
代码:
protected String modifyHtml(HttpServletRequest request, String html)
{
Document document = Jsoup.parse(html);
document.outputSettings().escapeMode(EscapeMode.xhtml);
Elements baseElements = document.select("base");
if (!baseElements.isEmpty())
{
Element base = baseElements.get(0);
base.attr("href", getBaseUrl(request));
}
return document.html();
}
最佳答案
除了(或代替)转义模式之外,您还需要设置语法:
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
关于java - JSoup 未生成有效的 XHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39365953/