2015-03-16 19 views
13
String body = "<br>"; 
Document document = Jsoup.parseBodyFragment(body); 
document.outputSettings().escapeMode(EscapeMode.xhtml); 
String str = document.body().html(); 
System.out.println(str); 

mong đợi: <br />Có thể chuyển HTML thành XHTML với Jsoup 1.8.1 không?

kết quả: <br>

thể Jsoup chuyển đổi giá trị HTML sang XHTML?

+0

Strange, nó hoạt động tốt đối với tôi. Tôi đã thử nghiệm nó bằng cách sử dụng phiên bản '1.7.2'. – Pshemo

+0

Không làm việc cho tôi, tôi đang sử dụng '1.8.1' – Henry

Trả lời

16

Xem 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(); 
} 
5

Bạn nên nói rằng cú pháp bạn muốn rời khỏi chuỗi trong HTML hay 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(); 
    } 
1

Bạn có thể sử dụng API JTidy để thực hiện việc này. Sử dụng jtidy-r938.jar

Bạn có thể sử dụng các phương pháp sau đây để có được xhtml từ html

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; 
    } 
Các vấn đề liên quan