jsoup换行

时间:2012-09-19 21:23:41

标签: jsoup

我们正在使用Jsoup.clean(String,Whitelist)来处理一些输入,并且看起来Jsoup在可接受的标签之前添加了一个无关的换行符。我见过一些人在互联网上发布这个问题,但是无法找到解决方案。

例如,假设我们有一个非常简单的字符串,其中包含一些粗体标记,如下所示:

String htmlToClean = "This is a line with <b>bold text</b> within it."                                                                                                                                                       
String returnString =  Jsoup.clean(htmlToClean, Whitelist.relaxed());
System.out.println(returnString);

对clean()方法的调用是这样的:

This is a line with \n<b>bold text</b> within it. 

请注意,在打开粗体标记之前附加了无关的“\ n”。我似乎无法在追加这一点的源头追踪(尽管我承认我是Jsoup的新手)。

有没有人遇到过这个问题,而且更好的是,已经找到了一些方法来避免这种额外的,不需要的字符以这种方式附加到字符串上?

2 个答案:

答案 0 :(得分:13)

嗯......还没有看到任何选择。

如果你解析Document中的html,你有一些输出设置:

Document doc = Jsoup.parseBodyFragment(htmlToClean);
doc.outputSettings().prettyPrint(false);

System.out.println(doc.body().html());

关闭prettyPrint后,您将获得以下输出:This is a line with <b>bold text</b> within it.

也许您可以编写自己的clean()方法,因为已实施的方法使用Document(您可以禁用prettyPrint):

原始方法:

public static String clean(String bodyHtml, Whitelist whitelist) {
    return clean(bodyHtml, "", whitelist);
}

public static String clean(String bodyHtml, String baseUri, Whitelist whitelist) {
    Document dirty = parseBodyFragment(bodyHtml, baseUri);
    Cleaner cleaner = new Cleaner(whitelist);
    Document clean = cleaner.clean(dirty);
    return clean.body().html();
}

答案 1 :(得分:7)

附录:

我刚刚下载了 Jsoup 1.7.1 ,在此版本中可以使用clean() - 自定义OutputSettings的方法:

String html = "This is a line with <b>bold text</b> within it.";

OutputSettings settings = new OutputSettings();
settings.prettyPrint(false);

String clean = Jsoup.clean(html, "", Whitelist.relaxed(), settings);

或更短:

String clean = Jsoup.clean(html, "", Whitelist.relaxed(), new OutputSettings().prettyPrint(false));

(实际上它与评论中发布的解决方案相同)