2012-07-04 3 views
4

나는 항상 <h2> 다음에 오는 첫 번째<ul>을 찾고, 단일 Jsoup select() 문을 사용하여 반복하지 않고 항상 찾으려고합니다.형제 또는 자손 이후에 오는 첫 번째 요소는 무엇입니까?

예를 들어, 그 <ul>이 HTML 코드에서와 같이 <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> 

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

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

아니면 <h2>의 형제의 후손 (반드시 직접 아이!)이 될 수 있습니다. 형제는 <h2> 이후 첫 번째 형제 요소 일 수도 있고 아닐 수도 있지만 <ul>입니다. 항상 첫 번째 <ul> 이후는 <h2>입니다. 예를 들어 :

Element h2 = select("h2 > span#targetSpan").first().parent(); 

을하지만 H2가 있으면, 어떻게 그것을 후 첫 <ul>를 찾을 수 있습니까 :

<!-- 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> 쉽게 찾을 수 있습니까?

+0

매우 관련 : http://stackoverflow.com/a/30089307/274502 – cregox

답변

3

당신은 당신의 자신의 루프를 피할 수 없다. 당신이 찾을 때까지 당신은 다음의 모든 요소 형제를 반복해야 <ul> 다음 :

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