gpt4 book ai didi

java - 在 JSoup 中合并相同的元素

转载 作者:行者123 更新时间:2023-12-02 08:52:08 25 4
gpt4 key购买 nike

我有这样的 HTML 字符串

<b>test</b><b>er</b>
<span class="ab">continue</span><span> without</span>

我想折叠相似且彼此所属的标签。在上面的示例中我想要

<b>tester</b>

因为标签具有相同的标签,没有任何进一步的属性或样式。但对于 span 标签,它应该保持不变,因为它有一个 class 属性。我知道我可以通过 Jsoup 在树上进行迭代。

Document doc = Jsoup.parse(input);
for (Element element : doc.select("b")) {
}

但我不清楚如何展望(我猜类似 nextSibling),但不知道如何折叠元素?

或者存在一个简单的正则表达式合并?

我可以自己指定的属性。不需要有一个通用的标签解决方案。

最佳答案

我的方法是这样的。代码中的注释

public class StackOverflow60704600 {

public static void main(final String[] args) throws IOException {
Document doc = Jsoup.parse("<b>test</b><b>er</b><span class=\"ab\">continue</span><span> without</span>");
mergeSiblings(doc, "b");
System.out.println(doc);

}

private static void mergeSiblings(Document doc, String selector) {
Elements elements = doc.select(selector);
for (Element element : elements) {
// get the next sibling
Element nextSibling = element.nextElementSibling();
// merge only if the next sibling has the same tag name and the same set of attributes
if (nextSibling != null && nextSibling.tagName().equals(element.tagName())
&& nextSibling.attributes().equals(element.attributes())) {
// your element has only one child, but let's rewrite all of them if there's more
while (nextSibling.childNodes().size() > 0) {
Node siblingChildNode = nextSibling.childNodes().get(0);
element.appendChild(siblingChildNode);
}
// remove because now it doesn't have any children
nextSibling.remove();
}
}
}
}

输出:

<html>
<head></head>
<body>
<b>tester</b>
<span class="ab">continue</span>
<span> without</span>
</body>
</html>

关于我为什么使用循环的更多说明 while (nextSibling.childNodes().size() > 0) 。原来是foriterator不能在这里使用,因为 appendChild添加子元素,但将其从源元素中删除,剩余的子元素将被移动。它可能在这里不可见,但当您尝试合并时会出现问题:<b>test</b><b>er<a>123</a></b>

关于java - 在 JSoup 中合并相同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60704600/

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