简体   繁体   English

检查节点在jsoup中具有明文?

[英]Check a node has plaintext in jsoup?

I know the method Element.hasText() can check if a node has text on jsoup but include link text. 我知道方法Element.hasText()可以检查节点是否在jsoup上具有文本,但包括链接文本。 I just want to check if it has plain text or not? 我只想检查是否有纯文本? Anyone can give me some solution? 有人可以给我一些解决方案吗? Thanks a lot 非常感谢

You cen use regex for this, here's an example: 您为此使用正则表达式,这是一个示例:

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

if the element has some text this will return false : 如果元素具有一些文本,则将返回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

Another solution: 另一个解决方案:

public static boolean hasOwnText(Element element)
{
    return !element.ownText().isEmpty();
}

with the html and doc from above: 上面的html和doc:

boolean hasText = hasOwnText(doc.select("p").first())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM