java - Jsoup - 提取文本

标签 java iteration jsoup text-extraction

我需要像这样从节点中提取文本:

<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 会忽略文本节点。

有没有办法迭代元素的内容来接收文本节点。例如

  • 文本节点 - 一些文本
  • 节点 - 带有标签
  • 文本节点 - 可能会放在这里。
  • 节点

    - 还有段落

  • 文本节点 - 更多文本可以没有段落
  • 节点
    -

最佳答案

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/>

关于java - Jsoup - 提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10177867/

相关文章:

java - 为什么我总是收到 IOException?

java - 什么 xml 解析器符合这些要求?

java - 通过 java 中的 websocket 与特定用户进行网络聊天

java - 我可以从 JUnit5 中的 @BeforeEach 中排除单个测试吗?

c++ - 删除C++ vector 中的字段

python - 一般如何将递归程序转换为迭代程序?

java - 使用 Jsoup 登录 Post 方法到 Asp.net 表单

java - 如何在graphview中的X轴上设置固定水平标签(Android Studio)

python - 优化遍历 numpy 数组

java - 使用 Jsoup 非递归地提取文本