JSoup 按顺序获取文本和内联图像

JSoup get text and inline images in order

我有一些 HTML 看起来像这样:

<tr>
  <td>
    Some text that is interrupted by an image here:
    <a href="/item" title="item"><img alt="imageName.png" src="linkhere" width="18" height="18"></a>
    and then continues here.
  </td>
</tr>

基本上我只需要一种方法来循环遍历此处的节点,并使用 JSoup 将文本或图像 alt 添加到字符串中,同时保持节点的顺序。

最后应该是这样的:

Some text that is interrupted by an image here: "imageName.png" and then continues here

到目前为止,我可以使用以下方法单独获取图像或单独获取文本:

element.text();
//or
element.select("img").attr("alt")

但我无法将它们都放入有序列表中。

有什么想法吗?

下面的代码应该给你你正在寻找的输出字符串。它基本上遍历文档中的所有节点并确定它们是文本节点还是元素。如果它们是文本节点,它将把它们添加到输出字符串中。如果它们是元素,它将检查图像子项并将替代文本添加到字符串中。

String test = "";

Element body = doc.getElementsByTag("body").first();
List<Node> childNodes = body.childNodes();

for(Node node : childNodes){

    if(node instanceof TextNode){
        // These are text nodes, lets see if they are empty or not and add them to the string.
        String nodeString = node.toString();
        if(nodeString != null && !nodeString.trim().isEmpty()){
            test += nodeString;
        }
    } else if (node instanceof Element) {
        // Here is an element, let's see if there is an image.
        Element element = (Element)node;
        Element image = element.children().select("img").first();

        if(image != null)
        {
            test += image.attr("alt");
        }
    }
}