我正在使用 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/