//Method for Strip HTML
public static String stripHtml(String inStr) {
boolean inTag = false;
char c;
StringBuffer outStr = new StringBuffer();
int len = inStr.length();
for (int i = 0; i < len; i++) {
c = inStr.charAt(i);
if (c == '<') {
inTag = true;
}
if (!inTag) {
outStr.append(c);
}
if (c == '>') {
inTag = false;
}
}
//Print to show that the this method is removing the necessary characters
System.out.println(outStr);
return outStr.toString();
}
所以我需要清理所有包含 <> 的输出以及它之间的所有内容,并且它仍然应该打印出剩余的字符。例如
input:app<html>le
expected:apple
但是,如果它只找到“<”或“>”,它也应该删除,但我的方法没有这样做。
input:app<le
output:app<le
expected:apple
请让我知道要修复什么。
最佳答案
尝试使用 JSoup 或 TagSoup 等 HTML 解析器来解析 HTML。
获得 DOM 后,只需在根元素上调用 getTextContent()
。
来自API documentation (Java 版本的行为各不相同): 该属性返回该节点及其后代的文本内容。 [...] 不执行序列化,返回的字符串不包含任何标记。
另请参阅
关于Java HTML 剥离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74648020/