Inserting Element in a Document using Jsoup

user1302575 picture user1302575 · Mar 30, 2012 · Viewed 15.8k times · Source

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>

Answer

B. Anderson picture B. Anderson · Mar 30, 2012

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:

  1. Select the first root element
  2. Grab the first child on that root element
  3. 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>