英文:
Using JSOUP How to Extract all elements from one tag & add in another tag?
问题
I can provide the translation of your request without any additional information:
我需要将文档中所有的<h2>标签设置为<a>标签。文档中包含一些带有<a>标签的<h2>标签,还有一些没有<a>标签的<h2>标签。
我需要:
- 如果
<h2>标签有<a>标签,则检查是否有id。如果没有,则设置id。 - 如果
<h2>标签没有<a>标签,则在<h2>标签中添加<a>标签。
例如,如果原始HTML如下:
Case 1:
<h2><a href="#headingABC"><span style="color:#009bd2;">My Heading ABC</span></a></h2>
然后,更改为(添加id):
<h2><a id="heading1" href="#headingXYZ"><span style="color:#009bd2;">My Heading ABC</span></a></h2>
Case 2:
<h2><span style="color:#009bd2;">My Heading ABC</span></h2>
然后,更改为(通过将h2中的所有元素移至a中添加a标签):
<h2><a id="heading1"><span style="color:#009bd2;">My Heading ABC</span></a></h2>
如何在Java(版本11)中使用JSOUP实现这一目标?
英文:
I need to set <a> tag to all <h2> tags in the document. Document contains few <h2> tags with <a> tags & few are without <a> tag.
I need to:
- If
<h2>has<a>tag then, check if it hasid. if it's not there then set theid - If
<h2>tag donesn't have<a>tag then add<a>tag in<h2>
e.g. if original HTML is like this:
Case 1:
<h2><a href="#headingABC"><span style="color:#009bd2;">My Heading ABC</span></a></h2>
Then, change it to (add id):
<h2><a id="heading1" href="#headingXYZ"><span style="color:#009bd2;">My Heading ABC</span></a></h2>
case 2:
<h2><span style="color:#009bd2;">My Heading ABC</span></h2>
Then, change it to (add a tag by moving all elements in h2 inside a):
<h2><a id="heading1"><span style="color:#009bd2;">My Heading ABC</span></a></h2>
How can I achieve this using JSOUP in Java (version 11).
答案1
得分: 1
Elements elements = doc.select("h2");
for (Element element : elements) {
Element firstChild = element.child(0);
if (firstChild.tagName().equals("a") && firstChild.attr("id").isEmpty()) {
firstChild.attr("id", "heading1");
} else {
firstChild.wrap("<a id=\"heading1\">");
}
}
英文:
Elements elements = doc.select("h2");
for (Element element : elements) {
Element firstChild = element.child(0);
if (firstChild.tagName().equals("a") && firstChild.attr("id").isEmpty()) {
firstChild.attr("id", "heading1");
} else {
firstChild.wrap("<a id=\"heading1\">");
}
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论