jsoup只剥离html标签而不换行符? [英] jsoup to strip only html tags not new line character?

查看:325
本文介绍了jsoup只剥离html标签而不换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有以下内容,我只想去除html标签,而不能去除换行符

I have below content in Java where I want to strip only html tags but not new line characters

<p>test1 <b>test2</b> test 3 </p> //line 1
<p>test4 </p> //line 2

如果我在富文本编辑器中打开以上内容,则第1行和第2行显示在不同的行中(不显示</p>标签).但是在记事本中,内容与</p>标签一起显示.删除我使用的所有html标记

If I open above content in text rich editor, line 1 and line 2 are displayed in different lines(without showing </p> tag).But in notepad content is shown along with </p> tags. To remove all html tags I used

Jsoup.parse(aboveContent).text()

它将删除所有html字符.但是它在记事本中的同一行中显示了所有的第1行和第2行. Jsoup也会以某种方式删除换行符.

It removes all html characters. But it shows all line 1 and line 2 in same line in notepad. Somehow Jsoup also removes newline character.

我尝试过的操作:-

我还尝试用\r\n替换</p>,然后删除html标签

I also tried replacing </p> with \r\n and then do to remove html tags

 Jsoup.parse(contentWith\r\n-Insteadof-</p>Tag ).text()

但Jsoup仍会在同一行中删除行尾字符(如在调试器中,我可以看到line1和line2).

but still Jsoup removes end of line character(as in the debugger I can see both line1 and line2) in same line.

我如何使Jsoup仅剥离html字符而不剥离换行符?

How I can make Jsoup to strip only html character but not new line character?

推荐答案

您会得到一行,因为text()删除了所有空白字符. 但是您可以使用StringBuilder并在其中插入每一行:

You get a single line because text() remove all whitepace characters. But you can use a StringBuilder and insert each line there:

final String html = "<p>test1 <b>test2</b> test 3 </p>"
                    + "<p>test4 </p>";

Document doc = Jsoup.parse(html);        
StringBuilder sb = new StringBuilder();


for( Element element : doc.select("p") )
{
    /*
     * element.text() returns the text of this element (= without tags).
     */
    sb.append(element.text()).append('\n');
}

System.out.println(sb.toString().trim());

输出:

test1 test2 test 3
test4

这篇关于jsoup只剥离html标签而不换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆