首页 > 解决方案 > 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" /> 

如果是这样,怎么做?还是有其他方法可用?

标签: jsoup

解决方案


是的,如果您调用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>

推荐阅读