2012-04-16 33 views
7

necesito para extraer texto de un nodo de la siguiente manera:Jsoup - la extracción de texto

<div> 
    Some text <b>with tags</b> might go here. 
    <p>Also there are paragraphs</p> 
    More text can go without paragraphs<br/> 
</div> 

y necesito construir:

Some text <b>with tags</b> might go here. 
Also there are paragraphs 
More text can go without paragraphs 

Element.text vuelve simplemente todo el contenido del div. Element.ownText - todo lo que no está dentro de elementos infantiles. Ambos están equivocados. Iterando a través de children ignora los nodos de texto.

Hay forma de iterar el contenido de un elemento para recibir nodos de texto también. P.ej.

  • nodo Text - Parte del texto
  • < Nodo B> - con etiquetas
  • nodo
  • texto - podría ir aquí.
  • Nodo < p> - También hay párrafos
  • nodo
  • texto - Más de texto puede ir sin párrafos
  • Nodo < br> - < vacío>

Respuesta

11

Element.children() devuelve un objeto Elements - una lista de Element objetos. Si observa la clase principal, Node, verá métodos para darle acceso a nodos arbitrarios, no solo Elementos, como Node.childNodes().

public static void main(String[] args) throws IOException { 
    String str = "<div>" + 
      " Some text <b>with tags</b> might go here." + 
      " <p>Also there are paragraphs</p>" + 
      " More text can go without paragraphs<br/>" + 
      "</div>"; 

    Document doc = Jsoup.parse(str); 
    Element div = doc.select("div").first(); 
    int i = 0; 

    for (Node node : div.childNodes()) { 
     i++; 
     System.out.println(String.format("%d %s %s", 
       i, 
       node.getClass().getSimpleName(), 
       node.toString())); 
    } 
} 

Resultado:

 
1 TextNode 
Some text 
2 Element <b>with tags</b> 
3 TextNode might go here. 
4 Element <p>Also there are paragraphs</p> 
5 TextNode More text can go without paragraphs 
6 Element <br/> 
+0

funciona perfectamente, gracias! –

3
for (Element el : doc.select("body").select("*")) { 

     for (TextNode node : el.textNodes()) { 

        node.text())); 

     } 

    } 
1

Suponiendo desea que el texto solamente (sin etiquetas) mi solución está por debajo.
Salida es:
Algunos textos con etiquetas pueden ir aquí. También hay párrafos. Más texto puede ir sin párrafos

public static void main(String[] args) throws IOException { 
    String str = 
       "<div>" 
      + " Some text <b>with tags</b> might go here." 
      + " <p>Also there are paragraphs.</p>" 
      + " More text can go without paragraphs<br/>" 
      + "</div>"; 

    Document doc = Jsoup.parse(str); 
    Element div = doc.select("div").first(); 
    StringBuilder builder = new StringBuilder(); 
    stripTags(builder, div.childNodes()); 
    System.out.println("Text without tags: " + builder.toString()); 
} 

/** 
* Strip tags from a List of type <code>Node</code> 
* @param builder StringBuilder : input and output 
* @param nodesList List of type <code>Node</code> 
*/ 
public static void stripTags (StringBuilder builder, List<Node> nodesList) { 

    for (Node node : nodesList) { 
     String nodeName = node.nodeName(); 

     if (nodeName.equalsIgnoreCase("#text")) { 
      builder.append(node.toString()); 
     } else { 
      // recurse 
      stripTags(builder, node.childNodes()); 
     } 
    } 
} 
1

puede utilizar para este propósito textNode:

List<TextNode> bodyTextNode = doc.getElementById("content").textNodes(); 
    String html = ""; 
    for(TextNode txNode:bodyTextNode){ 
     html+=txNode.text(); 
    }