I need to detect strictly adjacent elements with jsoup. For this I would use the example provided in How to detect strictly adjacent siblings but I need a working example for Jsoup - java.
Input
<div id="container">
<span class="highlighted">Paragraph 1</span>
<span class="highlighted">Paragraph 2</span>
This is just loose text.
<p class="highlighted">Paragraph 3</p>
</div>
What I'm trying to accomplish is to build a single element with the text of all sibling similar elements.
private String removeSimilarTags(String htmlContent){
org.jsoup.nodes.Document doc = Jsoup.parse(htmlContent);
Elements highlightedSpanElements = doc.select("span.highlighted"); //Selecting all spans with class highlight
for(Element span : highlightedSpanElements){
Element beforeEl = span.previousElementSibling();
if(span != null) //I need another function to verify if element has been already removed{
beforeEl.after("<span class='"+HIGHLIGHT+"'>"+mergeAdjacentSpans(span)+"</span>");
}
}
return doc.outerHtml();
}
private String mergeAdjacentSpans(Element span){
Element nextEl = span.nextElementSibling() != null ? span.nextElementSibling() : null;
String text = span.text();
if(nextEl != null && nextEl.tagName().equalsIgnoreCase(SPAN_TAG)
&& nextEl.classNames().contains(HIGHLIGHT)){
//Next Element is also a highlighted span
text = text.concat(" "+ mergeAdjacentSpans(spanEl));
}
span.remove();
return text;
}
And also I would like to have some insights of how to verify an element has been already removed. I cannot find a clear answer online.
Thank you guys !