繁体   English   中英

使用 Jsoup 在文档中插入元素

[英]Inserting Element in a Document using Jsoup

您好,我正在尝试在 Document 根元素中插入一个新的子元素,如下所示:

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

在上面的代码中,文档中只有一个根标签,因此基本上循环只会运行一次。

无论如何,该元素作为根元素“root”的最后一个元素插入。

有什么办法可以插入一个子元素作为第一个元素?

例子:

<root>
 <!-- New Element must be inserted here -->
 <child></child>
 <child></chidl> 
 <!-- But it is inserted here at the bottom insted  -->
</root>

看看这是否对你有帮助:

    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());

输出:

<root>
 <newchild></newchild>
 <child></child>
 <child></child>
</root>

为了破译,它说:

  1. 选择第一个根元素
  2. 获取该根元素上的第一个子元素
  3. 在那个孩子之前插入这个元素

您可以使用child方法中的任何索引来选择任何孩子

例子 :

    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());

输出:

<root>
 <child></child>
 <newchild></newchild>
 <child></child>
</root>

非常相似,使用 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