Inserting Element in a Document using Jsoup
Very similar, use prependElement() instead of appendElement() :
Document doc = Jsoup.parse(doc);
Elements els = doc.getElementsByTag("root");
for (Element el : els) {
Element j = el.prependElement("child");
}
See if this helps you out:
String html = "<root><child></child><child></chidl></root>";
Document doc = Jsoup.parse(html);
doc.selectFirst("root").child(0).before("<newChild></newChild>");
System.out.println(doc.body().html());
Output:
<root>
<newchild></newchild>
<child></child>
<child></child>
</root>
To decipher, it says:
- Select the first root element
- Grab the first child on that root element
- Before that child insert this element
You can select any child by using any index in the child
method
Example :
String html = "<root><child></child><child></chidl></root>";
Document doc = Jsoup.parse(html);
doc.selectFirst("root").child(1).before("<newChild></newChild>");
System.out.println(doc.body().html());
Output:
<root>
<child></child>
<newchild></newchild>
<child></child>
</root>