我的要求是保留每个标题h1之后的第一个div元素并删除所有其他div元素
<html>
<head> ...</head>
<body>
<div id="content">
<div> <span> data.....</span> </div>
<h1 id="head1">Customers </h1>
<div class="abc">
<table> <tr><td> Customer data</td>. </tr></table>
</div>
<div class="abc"> extra div </div>
<div class="abc"> one more extra div </div>
<h1 id="head2">Orders</h1>
<div class="abc">
<table>
<tr><td> Orders data</td></tr>
</table>
</div>
<div class="abc">extra div </div>
<div class="abc">one more extra div </div>
<h1 id="head3">Expenditures </h1>
<div class="abc"> an extra div</div>
<div class="abc"> one more extra div </div>
<h1 id="head4"> Depositors </h1>
<div class="abc"> an extra div </div>
<div class="abc">an one more extra div </div>
</div>
</body>
</html>
如何实现这一目标?
Mycode :(已修改)
Elements contElements = document.select("content");
for(Element e : contElements) {
if(e.tagName().equals("h1") && (!e.attr("id").equals("hd1") && !e.attr("id").equals("hd2")){
//remove h1 element with other id and all div's after this h1 element
}
else {
//keep h1 elemwnt and the first div comes after h1 and remove all other divs comes after this h1
}
如何在上面的代码段中填写以下建议的答案
我的预期输出:
<html>
<head> </head>
<body>
<div ID="content">
<div> <span> data.....</span> </div>
<h1 id="head1">Customers </h1>
<div class="abc">
<table> <tr><td> Customer data</td>. </tr></table>
</div>
<h1 id="head2">Orders</h1>
<div class="abc">
<table>
<tr><td> Orders data</td></tr>
</table>
</div>
</div>
</body>
</html>
答案 0 :(得分:2)
您可以使用伪选择器:gt(n):
所以你的选择器看起来像
Elements elements = document.select("h1 ~ div:gt(1)");
答案 1 :(得分:1)
您的方法的错误是它选择了h1之后的所有div元素。见here
您可以使用Elements elements = document.select("#content div:not(h1+div)");
这将删除#content中的所有div,它们之前没有h1元素。
答案 2 :(得分:0)
您可以检查以前的兄弟姐妹姓名是否为h1,如果不是,则将其删除?
Elements elements = document.select("h1 ~ div");
for (Element element : elements) {
if (!element.previousSibling().nodeName().equals("h1")) {
element.remove();
}
}