Перебирая элементы между последовательными <h>
элементами, кажется, все в порядке, кроме одной вещи. Текст, не принадлежащий ни одному тегу, как в <h1/>this<h1/>
. Чтобы обойти это, я реализовал функцию splitElemText
, чтобы получить этот текст. Сначала разделите весь родительский элемент, используя этот метод. Затем, кроме элемента, обработайте подходящую запись из разделенного текста. Удалите звонки на htmlToText
, если вы хотите сырой HTML.
/** Splits the text of the element <code>elem</code> by the children
* tags.
* @return An array of size <code>c+1</code>, where <copde>c</code>
* is the number of child elements.
* <p>Text after <code>n</code>th element is found in <code>[n+1]</code>.
*/
public static String[] splitElemText(Element elem)
{
int c = elem.children().size();
String as[] = new String[c + 1];
String sAll = elem.html();
int iBeg = 0;
int iChild = 0;
for (Element ch : elem.children()) {
String sChild = ch.outerHtml();
int iEnd = sAll.indexOf(sChild, iBeg);
if (iEnd < 0) { throw new RuntimeException("Tag " + sChild
+" not found in its parent: " + sAll);
}
as[iChild] = htmlToText(sAll.substring(iBeg, iEnd));
iBeg = iEnd + sChild.length();
iChild += 1;
}
as[iChild] = htmlToText(sAll.substring(iBeg));
assert(iChild == c);
return as;
}
public static String htmlToText(String sHtml)
{
Document doc = Jsoup.parse(sHtml);
return doc.text();
}