你为此使用正则表达式,这是一个例子:
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
Run Code Online (Sandbox Code Playgroud)
如果元素有一些文本,则返回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
Run Code Online (Sandbox Code Playgroud)
另一种方案:
public static boolean hasOwnText(Element element)
{
return !element.ownText().isEmpty();
}
Run Code Online (Sandbox Code Playgroud)
使用上面的html和doc:
boolean hasText = hasOwnText(doc.select("p").first())
Run Code Online (Sandbox Code Playgroud)