JSoup按顺序获取文本和嵌入式图像

时间:2018-07-25 14:17:12

标签: java html jsoup

我有一些看起来像这样的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添加到字符串中,从而保持节点的顺序。

最后它应该看起来像这样:

  

在此处被图片打断的某些文本:“ imageName.png”,然后在此处继续

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

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

但是我很难将它们都放入有序列表中。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

以下代码应为您提供所需的输出字符串。它基本上遍历文档中的所有节点,并确定它们是文本节点还是元素。如果它们是文本节点,它将把它们添加到输出字符串中。如果它们是元素,它将检查图像子项并将替代文本添加到字符串中。

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