使用JSOUP如何从一个标签中提取所有元素并添加到另一个标签中?

huangapple go评论131阅读模式
英文:

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>标签。

我需要:

  1. 如果<h2>标签有<a>标签,则检查是否有id。如果没有,则设置id
  2. 如果<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:

  1. If <h2> has <a> tag then, check if it has id. if it's not there then set the id
  2. 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(&quot;h2&quot;);
for (Element element : elements) {
	Element firstChild = element.child(0);
	if (firstChild.tagName().equals(&quot;a&quot;) &amp;&amp; firstChild.attr(&quot;id&quot;).isEmpty()) {
		firstChild.attr(&quot;id&quot;, &quot;heading1&quot;);
	} else {
		firstChild.wrap(&quot;&lt;a id=\&quot;heading1\&quot;&gt;&quot;);
	}
}

</details>



huangapple
  • 本文由 发表于 2023年4月20日 02:02:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定