2017-01-28 3 views
1

Ich habe eine html:Wie bekomme ich verwaisten Text mit Jsoup?

<span>This is the first text</span> 
More text here 
Another line of text 
<span>Text in the span</span> 
<span>Another text in span</span> 
This is another line 

Ich möchte, um alle Texte zu bekommen, so etwas wie dieses Array:

[ 
"Span:This is the first text", 
"More text here", 
"Another line of text", 
"Span:Text in the span", 
"Span:Another text in span", 
"This is another line", 
] 

Antwort

1

ich mit einer rekursiven Methode gehen würde, die Ihren Ausgang Tag und iteriert nimmt über seine Kindknoten. Drucken Sie den Inhalt für jeden Textknoten. Überprüfen Sie für jedes Element, ob es sich um untergeordnete Knoten handelt.

public static void main(String[] args) throws ParseException, IOException 
{ 
    //I put your HTML in the body tag in a local file 
    Document doc = Jsoup.parse(new File("input/20160505.html"), "UTF-8"); 
    Elements elements = doc.getElementsByTag("body"); 
    Element rootTag = elements.get(0); 
    printTextOfTag(rootTag); 
} 

public static void printTextOfTag(Element currentTag) 
{ 
    List<Node> nodes = currentTag.childNodes(); 
    for(Node n : nodes) 
    { 
     if(n instanceof TextNode) 
     { 
      System.out.println(((TextNode)n).text()); 
     } 
     else if(n instanceof Element) 
     { 
      printTextOfTag((Element)n); 
     } 
    } 
} 

Ausgabe

This is the first text 

More text here Another line of text 

Text in the span 



Another text in span 

This is another line