Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsoup: Extract all HTML between two blocks in CSS-less HTML

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?

like image 744
ef2011 Avatar asked Sep 04 '11 23:09

ef2011


1 Answers

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));
like image 151
soulcheck Avatar answered Oct 05 '22 02:10

soulcheck