兄弟姐妹或后代之后的第一个元素?

时间:2012-07-04 16:22:38

标签: jsoup

我总是试图找到<ul>之后的第一个 <h2>,最好不使用循环,使用单个Jsoup select()语句。

例如,<ul>可以是<h2>的兄弟,如此HTML代码段所示:

<!-- lots of things can come before -->

<h2 class="C" id="S3">
<button class="B">Click Me</button>
<span id="targetSpan">Target Span</span>
</h2>

<ul>
<li> List item 1</li>
<li> List item 2</li>
</ul>

<!-- lots of things can come after -->

或者它可以是<h2>的兄弟姐妹的后代(不一定是直接的孩子!)。兄弟姐妹可能是<h2>之后的第一个兄弟元素,但<ul> 总是 <{1}}之后的<ul>。例如:

<h2>

我可以轻松找到<!-- lots of things can come before --> <h2 class="C" id="S3"> <button class="B">Click Me</button> <span id="targetSpan">Target Span</span> </h2> <div> <ul> <li> List item 1</li> <li> List item 2</li> </ul> </div> <!-- lots of things can come after -->

<h2>

但是一旦我有了h2,我如何找到它之后的第一个Element h2 = select("h2 > span#targetSpan").first().parent(); ? (可能是兄弟或后代,我不控制HTML代码)

2 个答案:

答案 0 :(得分:3)

你无法避免自己的循环。您必须遍历所有下一个元素兄弟,直到找到下一个<ul>

  Element h2next = h2.nextElementSibling();
  do {
    ul = h2next.select("ul:not([class]))").first();         
  } while (h2next!=null && ul==null);

答案 1 :(得分:0)

也许你可以使用方法

nextElementSibling() 

从中获得UL。

http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#nextElementSibling()