使用Jsoup 1.8.1可以将HTML转换为XHTML吗?

28
String body = "<br>";
Document document = Jsoup.parseBodyFragment(body);
document.outputSettings().escapeMode(EscapeMode.xhtml);
String str = document.body().html();
System.out.println(str);

期望: <br />

结果: <br>

Jsoup能否将HTML转换为XHTML?


很奇怪,对我来说它运行得很好。我使用1.7.2版本进行了测试。 - Pshemo
对我不起作用,我正在使用 1.8.1 - Henry
4个回答

41

参见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();
}

4
您可能还希望: document.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml),将&nbsp;转换为&#xa0; - 因为前者在xhtml中不被允许。 - KajMagnus

7

您需要告诉语法,您希望将字符串保留在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;
    }

0
public String htmlToXhtml(String htmlContent) {
    Document doc = Jsoup.parse(htmlContent);
    doc = Jsoup.parse(doc.html(),Parser.xmlParser());
    String xhtml = doc.html();
    return xhtml;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接