在Java中轻松将HTML格式文本转换为纯文本(保留换行)

曾经终败给现在 2023-07-24 14:51 13阅读 0赞

第一步:引入Jsoup和lang和lang3的依赖:

Jsoup是HTML解析器
lang和lang3这两个包里有转换所需的工具类

  1. <dependency>
  2. <groupId>org.jsoup</groupId>
  3. <artifactId>jsoup</artifactId>
  4. <version>1.11.3</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>commons-lang</groupId>
  8. <artifactId>commons-lang</artifactId>
  9. <version>2.6</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.commons</groupId>
  13. <artifactId>commons-lang3</artifactId>
  14. <version>3.4</version>
  15. </dependency>

第二步:直接使用即可:

  1. import org.apache.commons.lang.StringEscapeUtils;
  2. import org.apache.commons.lang3.StringUtils;
  3. import org.jsoup.Jsoup;
  4. import org.jsoup.nodes.Document;
  5. import org.jsoup.safety.Whitelist;
  6. /**
  7. * @author Piconjo
  8. */
  9. public class Html2PlainText {
  10. public static String convert(String html)
  11. {
  12. if (StringUtils.isEmpty(html))
  13. {
  14. return "";
  15. }
  16. Document document = Jsoup.parse(html);
  17. Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
  18. document.outputSettings(outputSettings);
  19. document.select("br").append("\\n");
  20. document.select("p").prepend("\\n");
  21. document.select("p").append("\\n");
  22. String newHtml = document.html().replaceAll("\\\\n", "\n");
  23. String plainText = Jsoup.clean(newHtml, "", Whitelist.none(), outputSettings);
  24. String result = StringEscapeUtils.unescapeHtml(plainText.trim());
  25. return result;
  26. }
  27. }

使用测试:

在这里插入图片描述
在这里插入图片描述


发表评论

表情:
评论列表 (有 0 条评论,13人围观)

还没有评论,来说两句吧...

相关阅读