2017-03-13 12 views
2

heading-head1とhead2とhead1 head2とhead2 idの後ろにある最初のdiv要素を保持し、他のすべてのheading要素とdiv要素を削除する必要があります。 期待される出力を見てください私の要件について明確なアイデアを与えることができます。jsoupの選択したid要素の最初のdiv以外のすべてのdivを削除します。

入力HTML:以下

<html> 
    <head> ...</head> 
    <body> 
    <div id="main-content"> 
    <div class ="abc">sample data </div> 

    <h1 id="head1">Example 1 </h1> 
    <div class="abc"> 
     <table> <tr><td> table data 1</td></tr></table> 
    </div> 
    <div class="abc"> extra div </div> 
    <div class="abc"> one more extra div </div> 

    <h1 id="head2">Example 2</h1> 
    <div class="abc"> 
     <table> 
     <tr><td> table data 2</td></tr> 
    </table> 
    </div> 
    <div class="abc">extra div </div> 
    <div class="abc">one more extra div </div> 

    <h1 id="head3">Example 3</h1> 
    <div class="abc"> an extra div</div> 
    <div class="abc"> one more extra div </div> 

    <h1 id="head4"> Example 4</h1> 
    <div class="abc"> an extra div </div> 
    <div class="abc">an one more extra div </div> 

    </div> 
    </body> 
    </html> 

は私のコードです:

Elements contElements = document.select("main-content"); 
    for(Element e : contElements) { 
     if(e.tagName().equals("h1") &&  (!e.attr("id").equals("head1") && !e.attr("id").equals("head2")){ 
    //remove h1 element with other id and all div's after this h1 element 
    document.select("h1 ~ div "); 
    e.remove(); 
    } 
else { 
     //keep h1 element and the first div comes after h1 and remove all other divs comes after this h1 
    document.select("h1 ~ div"); 
    } 

しかし、予想通り上記のコードは動作しません。期待される成果を達成するために何が欠けていますか?

私の期待出力:

<html> 
    <head> </head> 
    <body> 
    <div ID="main-content"> 
     <div class="abc"> sample data </div> 

     <h1 id="head1">Example 1</h1> 
     <div class="abc"> 
     <table> <tr><td> table data</td></tr></table> 
     </div> 

    <h1 id="head2">Example 2 </h1> 
     <div class="abc"> 
     <table> <tr><td> table data</td></tr></table> 
     </div> 

    </div> 
    </body> 
    </html> 

答えて

1

あなたが代わりに明示的なループのCSSセレクタを使用することができます。

を選択し、id#head2#head1ないではありませんすべてのh1要素削​​除:

document.select("#main-content h1:not(#head1):not(#head2)").remove(); 

選択をし、すぐにh1が先行していないすべてのdiv要素削​​除:

document.select("#main-content div:not(h1 + div)").remove(); 

を直後の子孫、すなわち#main-contentにのみ操作したい場合は、puそれの直後にt >

関連する問題