我们使用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);
Run Code Online (Sandbox Code Playgroud)
调用clean()方法的原因是这样的:
This is a line with \n<b>bold text</b> within it.
Run Code Online (Sandbox Code Playgroud)
请注意,在打开粗体标记之前附加了无关的"\n".我似乎无法在追加这一点的源头追踪(尽管我承认我是Jsoup的新手).
有没有人遇到这个问题,更好的是,已经找到一些方法来避免这种额外的,不需要的字符以这种方式附加到字符串?
oll*_*llo 13
嗯......还没有看到任何选择.
如果解析html,Document你有一些输出设置:
Document doc = Jsoup.parseBodyFragment(htmlToClean);
doc.outputSettings().prettyPrint(false);
System.out.println(doc.body().html());
Run Code Online (Sandbox Code Playgroud)
随着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();
}
Run Code Online (Sandbox Code Playgroud)
我刚刚下载了Jsoup 1.7.1,在这个版本中可以使用clean()自定义的-method 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);
Run Code Online (Sandbox Code Playgroud)
或更短:
String clean = Jsoup.clean(html, "", Whitelist.relaxed(), new OutputSettings().prettyPrint(false));
Run Code Online (Sandbox Code Playgroud)
(实际上它与评论中发布的解决方案相同)
| 归档时间: |
|
| 查看次数: |
5080 次 |
| 最近记录: |