【问题标题】:Is it possible to convert HTML into XHTML with Jsoup 1.8.1?是否可以使用 Jsoup 1.8.1 将 HTML 转换为 XHTML?
【发布时间】:2015-05-19 04:08:21
【问题描述】:
String body = "<br>";
Document document = Jsoup.parseBodyFragment(body);
document.outputSettings().escapeMode(EscapeMode.xhtml);
String str = document.body().html();
System.out.println(str);

期望:&lt;br /&gt;

结果:&lt;br&gt;

Jsoup 可以将值 HTML 转换为 XHTML 吗?

【问题讨论】:

  • 奇怪,它对我来说很好用。我使用1.7.2 版本对其进行了测试。
  • 不适合我,我正在使用1.8.1

标签: java html xhtml jsoup


【解决方案1】:

Document.OutputSettings.Syntax.xml:

private String toXHTML( String html ) {
    final Document document = Jsoup.parse(html);
    document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);    
    return document.html();
}

【讨论】:

  • 您很可能还想:document.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml)&amp;nbsp; 转换为 &amp;#xa0; — xhtml 中不允许使用前者。
【解决方案2】:

你应该告诉那个语法你想把字符串留在 HTML 或 XML 中。

public String parserXHtml(String html) {
        org.jsoup.nodes.Document document = Jsoup.parseBodyFragment(html);
        document.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml); //This will ensure the validity
        document.outputSettings().charset("UTF-8");
        return document.toString();
    }

【讨论】:

    【解决方案3】:

    您可以使用 JTidy API 来执行此操作。使用 jtidy-r938.jar

    可以使用以下方法从html中获取xhtml

    public static String getXHTMLFromHTML(String inputFile,
                String outputFile) throws Exception {
    
            File file = new File(inputFile);
            FileOutputStream fos = null;
            InputStream is = null;
            try {
                fos = new FileOutputStream(outputFile);
                is = new FileInputStream(file);
                Tidy tidy = new Tidy(); 
                tidy.setXHTML(true); 
                tidy.parse(is, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally{
                if(fos != null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        fos = null;
                    }
                    fos = null;
                }
                if(is != null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        is = null;
                    }
                    is = null;
                }
            }
    
            return outputFile;
        }
    

    【讨论】:

      猜你喜欢
      • 2011-07-08
      • 2019-10-25
      • 1970-01-01
      • 2014-03-30
      • 2016-06-07
      • 1970-01-01
      • 2012-12-30
      • 2015-05-20
      • 2016-12-30
      相关资源
      最近更新 更多