Question

What would be an optimal way, using Jsoup, to extract all HTML (either to a String, Document or Elements) between two blocks that conform to this pattern:

<strong>
 {any HTML could appear here, except for a <strong> pair}
</strong>

 ...
 {This is the HTML I need to extract. 
  any HTML could appear here, except for a <strong> pair}
 ... 

<strong>
 {any HTML could appear here, except for a <strong> pair}
</strong>

Using a regex this could be simple, if I apply it on the entire body.html():

(<strong>.+</strong>)(.+)(<strong>.+</strong>)
                       ^
                       +----- There I have my HTML content

But as I learned from a similar challenge, performance could be improved (even if the code is slightly longer) if I use an already Jsoup-parsed DOM -- except that this time neither Element.nextSibling() nor Element.nextElementSibling() can come to the rescue.

I searched for something like jQuery's nextUntil in Jsoup, for example, but couldn't really find something similar.

Is it possible to come up with something better than the above regex-based approach?

Was it helpful?

Solution

I don't know if it's faster but maybe something like this will work:

Elements strongs = doc.select("strong");
Element f = strongs.first();
Element l = strongs.last();
Elements siblings = f.siblingElements();
List<Element> result = siblings.subList(siblings.firstIndexOf(f) + 1,siblings.lastIndexOf(l));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top