java html转txt_JAVA过滤标签实现将html内容转换为文本的方法示例
时间: 2024-03-01 09:51:14 浏览: 23
可以使用Jsoup库来过滤HTML标签,将HTML内容转换为纯文本。以下是一个示例代码:
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HtmlToTxt {
public static String htmlToTxt(String html) {
Document doc = Jsoup.parse(html);
Elements elements = doc.getAllElements();
StringBuilder sb = new StringBuilder();
for (Element element : elements) {
if (element.isBlock()) {
sb.append("\n");
}
if (element.hasText()) {
sb.append(element.text());
}
}
return sb.toString();
}
}
```
在上面的代码中,我们首先将HTML字符串解析为一个Jsoup的`Document`对象,然后遍历所有元素,如果元素是块级元素,我们就在输出中添加一个换行符;如果元素包含文本内容,我们就将其文本添加到输出中。
使用上面的代码,可以轻松地将HTML内容转换为纯文本:`
```java
String html = "<p>Hello, <strong>world</strong>!</p>";
String txt = HtmlToTxt.htmlToTxt(html);
System.out.println(txt); // Hello, world!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)