如何从Jsoup获取未格式化的html

时间:2014-11-10 12:54:21

标签: java html-parsing jsoup html-parser

String testCases[] = {
        "<table><tbody><tr><td><div><inline>Normal Line Text</inline><br/></div></td></tr></tbody></table>",                  
};
for (String testString : testCases) {
    Document doc = Jsoup.parse(testString,"", Parser.xmlParser());
    Elements elements = doc.select("table");
    for (Element ele : elements) {
        System.out.println("===============================================");
        System.out.println(ele.html());                //Formatted
        System.out.println("-----------------------------------------------");
        System.out.println(ele.html().trim().replace("\n","").replace("\r",""));    //Notice the Difference
    }
}

输出:

===============================================
<tbody>
 <tr>
  <td>
   <div>
    <inline>
     Normal Line Text
    </inline>
    <br />
   </div></td>
 </tr>
</tbody>
-----------------------------------------------
<tbody> <tr>  <td>   <div>    <inline>     Normal Line Text    </inline>    <br />   </div></td> </tr></tbody>

由于JSoup完成了格式化,textNodes的值会更改为包含换行符。

在测试用例中将<inline>更改为<span>似乎工作正常,但不幸的是,我们有遗留数据/ html包含由redactor生成的<inline>标记。

1 个答案:

答案 0 :(得分:1)

试试这个:

Document doc = Jsoup.parse(testString,"", Parser.xmlParser());
doc.outputSettings().prettyPrint(false);

希望它有所帮助。

取自https://stackoverflow.com/a/19602313/3324704