【问题标题】:Does OutputSettings charset also change meta Content-Type?OutputSettings 字符集是否也会更改元内容类型?
【发布时间】:2021-01-29 18:16:59
【问题描述】:

我必须将字符串从内容类型 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


    【解决方案1】:

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

    【讨论】:

    • 我明白了。您自己删除元标记,因为 jsoup 不会为您执行此操作。
    • 在这种情况下,当我们从 HTML 更改为 XML 时,我们手动执行此操作。如果只是更改字符集并使用标准元标记,则 jsoup 会自动内联更新该值。
    猜你喜欢
    • 2017-01-16
    • 2017-10-16
    • 2023-04-09
    • 2010-12-20
    • 2014-01-02
    • 2013-04-19
    • 2011-05-30
    • 2021-07-27
    • 1970-01-01
    相关资源
    最近更新 更多