Hello I'm trying to insert a new child element in a Document root element like this:
Document doc = Jsoup.parse(doc);
Elements els = doc.getElementsByTag("root");
for (Element el : els) {
Element j = el.appendElement("child");
}
In the above code only one root tag is in the document so essentially the loop will just run once.
Anyway, the element is inserted as the last element of the root element "root."
Is there any way I can insert a child element as the first element?
Example:
<root>
<!-- New Element must be inserted here -->
<child></child>
<child></chidl>
<!-- But it is inserted here at the bottom insted -->
</root>
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:
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>