gpt4 book ai didi

java - 删除除 jsoup 中 h1 标签之后第一个 div 之外的所有 div 元素

转载 作者:行者123 更新时间:2023-12-01 20:53:47 24 4
gpt4 key购买 nike

我的要求是保留每个标题 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>

如何实现这一目标?

我的代码:(已修改)

 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>

最佳答案

您可以使用伪选择器 :gt(n): 过滤第一个以上的 div:

所以你的选择器看起来像

Elements elements = document.select("h1 ~ div:gt(1)");

关于java - 删除除 jsoup 中 h1 标签之后第一个 div 之外的所有 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42715326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com