gpt4 book ai didi

java - 删除给定标签后的所有元素

转载 作者:行者123 更新时间:2023-11-30 08:05:50 24 4
gpt4 key购买 nike

标签结构如下:

<div class="some-class">
<h3>Foo</h3>
<p>...</p>
<p>...</p>
<h3>Bar</h3>
<p>...</p>
<p>...</p>
...

现在,我想在找到 h3 标记后删除 some-class 标记内的所有元素。 JSoup 中是否有像 JavaScript 那样的 nextAll() 方法?

现在我有

for (Element el : doc.select("div") {
if (el.className().equalsIgnoreCase("some-class") {
for (Element e : el.select("h3") {
if (e.hasText().equalsIgnoreCase("Bar") {
removeAllNextPTags();
}
}
}
}

有什么想法吗?

最佳答案

Is there a nextAll() method in JSoup

您可以使用nextElementSibling()在元素基础上或 nextElementSibling()基于节点。

我不完全确定我的理解是否正确,但是您想删除 h3 之后的所有 元素还是仅删除 p 元素(直到另一个 h3 发生!?)?

以下是如何删除所有 p 元素,从具有给定文本的 h3 元素开始 - 直到找到另一个 h3:

public void removeChilds(Element root, String h3Text)
{
final Element h3Start = root.select("h3:contains(" + h3Text + ")").first();
final int h3Idx = h3Start.siblingIndex();

for( Element e : h3Start.siblingElements() )
{
// Skip all nodes before the relevant h3 element
if( e.siblingIndex() > h3Idx )
{
switch(e.tagName())
{
case "p":
e.remove();
break;
case "h3":
/* Stop if there's a h3 */
return;
default:
/* Stop also if there's any non-p element!? */
return;
}
}
}
}

对所有具有给定文本的 h3 执行此操作 - 例如。多个<h3>Foo</h3> - 带有子元素的元素 - 您可以替换 first()对找到的元素进行循环(这就是 select() 返回的内容)。

关于java - 删除给定标签后的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31135777/

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