微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

OutputSettings 字符集是否也会更改元内容类型?

如何解决OutputSettings 字符集是否也会更改元内容类型?

我必须将字符串从内容类型 text/html 转换为 application/xhtml+xml 并从 windows-1252 转换为 UTF-8

charset
public Document.OutputSettings charset​(Charset charset)
Update the document's output charset. 

html 源代码包含类似内容

<Meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

当前的 xml/html 输出

<Meta http-equiv="Content-Type" content="text/html; charset=windows-1252" /> 

当前指令是

org.jsoup.nodes.Document doc = Jsoup.parse(htmlString);
doc.outputSettings(new OutputSettings().Syntax(Syntax.xml).escapeMode(EscapeMode.xhtml));

OutputSeetings 是否能够创建类似的字符串

<Meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" /> 

如果是这样,怎么办?或者还有其他可用的方法吗?

解决方法

是的,如果您调用 Document#charset(charset) 方法,jsoup 会执行此操作。除了更新文档输出设置外,它还会向文档添加适当的 HTML 或 XML 以指定字符集。

例如:

String html = "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\"><body>Hello";
Document doc = Jsoup.parse(html);

doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml); // specify that we want XML output
doc.charset(StandardCharsets.UTF_8); // update the charset - also adds the <?xml encoding> instruction
doc.select("meta[content~=charset]").remove(); // Remove the obsolete HTML meta

System.out.println(doc.html());
}

给我们:

<?xml version="1.0" encoding="UTF-8"?>
<html>
 <head></head>
 <body>
  Hello
 </body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。