简体   繁体   中英

Inserting Element in a Document using Jsoup

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:

  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>

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM