gpt4 book ai didi

java - 使用jsoup将html转换为纯文本时如何保留换行符?

转载 作者:IT老高 更新时间:2023-10-28 11:29:51 43 4
gpt4 key购买 nike

我有以下代码:

 public class NewClass {
public String noTags(String str){
return Jsoup.parse(str).text();
}


public static void main(String args[]) {
String strings="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN \">" +
"<HTML> <HEAD> <TITLE></TITLE> <style>body{ font-size: 12px;font-family: verdana, arial, helvetica, sans-serif;}</style> </HEAD> <BODY><p><b>hello world</b></p><p><br><b>yo</b> <a href=\"http://google.com\">googlez</a></p></BODY> </HTML> ";

NewClass text = new NewClass();
System.out.println((text.noTags(strings)));
}

我得到了结果:

hello world yo googlez

但我想断线:

hello world
yo googlez

我看过 jsoup's TextNode#getWholeText()但我不知道如何使用它。

如果有 <br>在我解析的标记中,如何在结果输出中换行?

最佳答案

保留换行符的真正解决方案应该是这样的:

public static String br2nl(String html) {
if(html==null)
return html;
Document document = Jsoup.parse(html);
document.outputSettings(new Document.OutputSettings().prettyPrint(false));//makes html() preserve linebreaks and spacing
document.select("br").append("\\n");
document.select("p").prepend("\\n\\n");
String s = document.html().replaceAll("\\\\n", "\n");
return Jsoup.clean(s, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));
}

满足以下要求:

  1. 如果原始 html 包含换行符(\n),则保留
  2. 如果原始 html 包含 br 或 p 标签,它们将被翻译成换行符(\n)。

关于java - 使用jsoup将html转换为纯文本时如何保留换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5640334/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com