java - Jsoup 解析器删除带有 '<' 和 '>' 的单词

标签 java jsoup

我正在使用 Jsoup.parse()从字符串中删除 html 标签。但是我的字符串像 <name> 这样的词还。

问题是 Jsoup.parse() 也删除了它。我不是因为该文本有 < 和 >。我也不能只从文本中删除 < 和 >。我该怎么做。

String s1 = Jsoup.parse("<p>Hello World</p>").text();
//s1 is "Hello World". Correct

String s2 = Jsoup.parse("<name>").text();
//s2 is "". But it should be <name> because <name> is not a html tag

最佳答案

I'm using the Jsoup.parse() to remove html tags from a String.

您想使用 Jsoup#clean方法。之后您还需要一些手动工作,因为 Jsoup 仍会看到 <name>作为 HTML 标记。

// Define the list of words to preserve...
String[] myExceptions = new String[] { "name" }; 
int nbExceptions = myExceptions.length;

// Build a whitelist for Jsoup...
Whitelist myWhiteList = Whitelist.simpleText().addTags(myExceptions);

// Let Jsoup remove any html tags...
String s2 = Jsoup.clean("<name>", myWhiteList);

// Complete the initial html tags removal...
for (int i = 0; i < nbExceptions; i++) {
    s2 = s2.replaceAll("<" + myExceptions[i] + ">.+?</" + myExceptions[i] + ">", "<" + myExceptions[i] + ">");
}

System.out.println(">>" + s2);

输出

>><name>

引用资料

关于java - Jsoup 解析器删除带有 '<' 和 '>' 的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38735854/

相关文章:

java - "No Suitable Driver for jdbc:mysql..."错误

java - Jsoup - 如何检查元素是否属于特定类?

java - 提取 HTML <br> 标签中的文本 JSOUP

java - 如何使用jsoup提取某些标签后的文本

c++ - Jsoup 类似于 C++ 的 html 解析器

java - 从 HashMap 获取最大 Set 大小

java - Android listView右滑时子位置错误

java - 非 spring web 应用程序是否可以并行 Spring-MVC 应用程序?

java - 文件的最后修改时间是一个 13 位数字。这是什么意思?

java - 费马分解方法不起作用