Jsoup - 提取文本

问题描述:

我需要从这样的节点中提取文本:Jsoup - 提取文本

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

而且我需要建立:

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

Element.text刚刚返回的div的所有内容。 Element.ownText - 所有不在孩子内部的元素。两者都是错误的。遍历children会忽略文本节点。

是否有办法迭代元素的内容以接收文本节点。例如。

  • 文本节点 - 一些文本
  • 节点< B> - 与标签
  • 文本节点 - 可能会去这里。
  • 节点< P> - 还有一些段落
  • 文本节点 - 更多的文字可以去无段落
  • 节点< BR> - <空>

Element.children()返回Elements对象 - 列表Element对象。查看父类Node,您将看到一些方法可让您访问任意节点,而不仅仅是元素,例如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())); 
    } 
} 

结果:

 
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

完美的作品,谢谢! – 2012-04-16 20:49:47

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

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

        node.text())); 

     } 

    } 

假设你想纯文本(无标签)我的解决方案如下。
输出结果为:
某些带有标记的文字可能会在此处显示。还有段落。更多的文字可以去无段落

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()); 
     } 
    } 
} 

您可以使用TextNode用于此目的:

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