Skip to content

Instantly share code, notes, and snippets.

@subchen
Created November 7, 2013 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subchen/7352437 to your computer and use it in GitHub Desktop.
Save subchen/7352437 to your computer and use it in GitHub Desktop.
Using Jsoup to automatic bulleted for headers in HTML
private static String autolist(String html) {
Document document = Jsoup.parse(html);
Elements headers = document.select("h1,h2,h3,h4,h5,h6");
int n[] = new int[] { 0, 0, 0, 0, 0, 0, 0 };
for (Element header : headers) {
String tag = header.tagName().toLowerCase();
String text = header.text();
if ("h1".equals(tag)) {
header.text((++n[1]) + " " + text);
n[2] = n[3] = n[4] = n[5] = n[6] = 0;
} else if ("h2".equals(tag)) {
header.text((n[1]) + "." + (++n[2]) + " " + text);
n[3] = n[4] = n[5] = n[6] = 0;
} else if ("h3".equals(tag)) {
header.text((n[1]) + "." + (n[2]) + "." + (++n[3]) + " " + text);
n[4] = n[5] = n[6] = 0;
} else if ("h4".equals(tag)) {
header.text((n[1]) + "." + (n[2]) + "." + (n[3]) + "." + (++n[4]) + " " + text);
n[5] = n[6] = 0;
} else if ("h5".equals(tag)) {
header.text((n[1]) + "." + (n[2]) + "." + (n[3]) + "." + (n[4]) + "." + (++n[5]) + " " + text);
n[6] = 0;
} else if ("h6".equals(tag)) {
header.text((n[1]) + "." + (n[2]) + "." + (n[3]) + "." + (n[4]) + "." + (n[5]) + "." + (++n[6]) + " " + text);
}
}
return document.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment