【问题标题】:Get next element of specific tag type in jsoup在jsoup中获取特定标签类型的下一个元素
【发布时间】:2014-05-11 03:43:17
【问题描述】:

我正在使用 jsoup 遍历一个元素列表,但需要定期找到一个不直接出现在当前元素之后的元素。

例如,如果我正在迭代并找到一个 img 标记,我想找到在该 img 标记之后出现的下一个 a 标记。但是,两者之间可能有一些标签。

下面是一些示例代码:

for (Element e : elements) {
    if (e.tagName().equalsIgnoreCase("img")) {
        // Do some stuff with "img" tag
        // Now, find the next tag in the list with tag <a>
    }

    // Do some other things before the next loop iteration
}

我认为像 e.select("img ~ a") 这样的东西应该可以工作,但它没有返回任何结果。

在 jsoup 中有什么好的方法?

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    这似乎是实现既定目标的一种方式。不确定它是最有效的,但它是最直接的。

    Element node = e.nextElementSibling();
    while (node != null && !node.tagName().equalsIgnoreCase("a")) {
        node = node.nextElementSibling();
    }
    

    我希望有一种方法可以运行相当于e.nextElementSibling("a")。也许我可以为 jsoup 做出贡献;-)

    【讨论】:

      【解决方案2】:

      使用 nextElementSibling() 方法。

      在 if 语句中添加以下代码:

      Element imgNext = e.nextElementSibling();
      do {
          Element a = imgNext.select("a[href]").first();         
      } while (imgNext!=null && a==null);
      

      【讨论】:

      • 这实际上是一个无限循环。如果第一次没有发现“a”不是null,那么循环将永远不会结束。
      猜你喜欢
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      相关资源
      最近更新 更多