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

问题描述 投票:0回答:4
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 吗?

java html xhtml jsoup
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();
}

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.