#第一步:引入Jsoup和lang和lang3的依赖:
Jsoup是HTML解析器lang和lang3这两个包里有转换所需的工具类
< groupId > org.jsoup groupId>
< artifactId > jsoup artifactId>
< version > 1.11 .3 < / version >
< / dependency >
< dependency >
< groupId > commons - lang groupId>
< artifactId > commons - lang artifactId>
< version > 2.6 < / version >
< / dependency >
< dependency >
< groupId > org.apache.commons groupId>
< artifactId > commons - lang3 artifactId>
< version > 3.4 < / version >
< / dependency>
复制代码
#第二步:直接使用即可:
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
/**
* @author Piconjo
*/
public class Html2PlainText {
public static String convert( String html )
{
if ( StringUtils.isEmpty( html ) )
{
return("");
}
Documentdocument= Jsoup.parse( html );
Document.OutputSettings outputSettings= new Document.OutputSettings().prettyPrint( false );
document.outputSettings( outputSettings );
document.select( "br" ).append( "\\n" );
document.select( "p" ).prepend( "\\n" );
document.select( "p" ).append( "\\n" );
StringnewHtml= document.html().replaceAll( "\\\\n", "\n" );
StringplainText= Jsoup.clean( newHtml, "", Whitelist.none(), outputSettings );
Stringresult= StringEscapeUtils.unescapeHtml( plainText.trim() );
return(result);
}
}
复制代码
#使用测试:

感谢阅读 喜欢学习的朋友们可以关注下小编 小编会定期更新优质文章。
本文介绍如何使用Jsoup库解析HTML并转换为纯文本,包括引入依赖、代码实现和测试示例。重点在于使用StringUtils和Jsoup的配合来清理HTML,去除多余标签,便于阅读和处理。
4537

被折叠的 条评论
为什么被折叠?



