2015-10-19 31 views
0

我在我的HTML标签等:如何在Jsoup中获取仅在java中的特定标记的消息?

<p class="outter"> 
    <strong class="inner">not needed message</strong> 
    NEEDED MESSAGE 
</p> 

我试图提取 “被需要MESSAGE”

但如果我做这样的事情:

String results = document.select("p.outter").text(); 
System.out.println(results); 

它打印:

不需要messageNEEDED MESSAGE

所以,问题是:

我怎样才能得到一个特定的标签文本不从其内标签的文本?

回答

1

选择段落后,您可以使用ownText()。例如

package com.stackoverflow.answer; 

import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.select.Elements; 
import org.jsoup.nodes.Element; 

public class HtmlParserExample { 

    public static void main(String[] args) { 
     String html = "<p class=\"outter\"><strong class=\"inner\">not needed message</strong>NEEDED MESSAGE</p>"; 
     Document doc = Jsoup.parse(html); 
     Elements paragraphs = doc.select("p"); 
     for (Element p : paragraphs) 
      System.out.println(p.ownText()); 
    } 

} 
+0

从不新约'ownText()',TXT – nafas

1

一种解决方案可能是仅选择TextNode元素。在下面找到一小段代码。

String html = "<p class=\"outter\">\n" 
     + " <strong class=\"inner\">not needed message</strong>\n" 
     + " NEEDED MESSAGE\n" 
     + "</p>"; 
Document doc = Jsoup.parse(html); 
Elements elements = doc.select("p.outter"); 
for (Element element : elements) { 
    // as mentioned by luksch 
    System.out.println("ownText = " + element.ownText()); 

    // or manually based on the node type 
    for (Node node : element.childNodes()) { 
     if (node instanceof TextNode) { 
      System.out.println("node = " + node); 
     } 
    } 
} 

输出

node = 
node = NEEDED MESSAGE 

所以你需要过滤根据您的需要输出。例如。跳过空的。

1

使用Jsoup的ownText()方法:

String results = document.select("p.outter").ownText(); 
System.out.println(results); 
+0

约'ownText()从来没有新的非常有帮助',非常有帮助的txt – nafas

相关问题