我知道 Element.hasText() 方法可以检查节点是否在 jsoup 上有文本但包含链接文本。我只是想检查它是否有纯文本?任何人都可以给我一些解决方案吗?非常感谢
问问题
1773 次
1 回答
7
您为此使用正则表达式,这是一个示例:
final String html = "<p><span>spantext</span></p>"; // p-tag with no own text, but a child which has one
Document doc = Jsoup.parse(html);
// Check if the 'p'-tag has own text
boolean hasText = doc.select("p").is("p:matchesOwn(^$)"); // --> true, p has no own text
如果元素有一些文本,这将返回false
:
final String html = "<p>owntext<span>spantext</span></p>";
Document doc = Jsoup.parse(html);
// Check if the 'p'-tag has own text
boolean hasText = doc.select("p").is("p:matchesOwn(^$)"); // --> false, p has some own text
另一种解决方案:
public static boolean hasOwnText(Element element)
{
return !element.ownText().isEmpty();
}
使用上面的 html 和 doc:
boolean hasText = hasOwnText(doc.select("p").first())
于 2013-01-31T13:52:51.907 回答