简体   繁体   English

使用 Jsoup 在文档中插入元素

[英]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 根元素中插入一个新的子元素,如下所示:

    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."无论如何,该元素作为根元素“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您可以使用child方法中的任何索引来选择任何孩子

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() :非常相似,使用 prependElement() 而不是 appendElement() :

Document doc = Jsoup.parse(doc);
Elements els = doc.getElementsByTag("root");
for (Element el : els) {
    Element j = el.prependElement("child");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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