jsoup - 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>
推荐阅读
- macos - errors when building electron from source with gn and ninja on Mac OS 10.15
- arrays - 将简单代码集成到复杂代码中
- java - 更改 BroadcastReceiver 中的变量
- reactjs - 在远程服务器上运行开发时,webpack 热重载不起作用
- node.js - 使用 socket.io 向特定客户端发送消息,同时套接字 id 快速变化
- orientdb - 如何在 OrientDB 中遍历并找到所有最长的路径?
- c# - iText 使用外部签名 WebService 创建签名 PDF
- java - 如何修复 "{"name":"error","attributes":{"message":"Exception occurred in the Test Runner." 在 VS 代码中
- google-bigquery - BigQuery 将 rank / percent_rank 应用于带有 WHERE 子句的列
- javascript - React+Firebase:如何将项目添加到 Firebase 实时数据库中