使用Jsoup在文档中插入元素

12 java parsing jsoup

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

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

在上面的代码中,文档中只有一个根标记,因此循环只运行一次.

无论如何,元素作为根元素"root"的最后一个元素插入.

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

例:

<root>
 <!-- New Element must be inserted here -->
 <child></child>
 <child></chidl> 
 <!-- But it is inserted here at the bottom insted  -->
</root>
Run Code Online (Sandbox Code Playgroud)

小智 16

看看这是否有助于你:

    String html = "<root><child></child><child></chidl></root>";
    Document doc = Jsoup.parse(html);
    doc.select("root").first().children().first().before("<newChild></newChild>");
    System.out.println(doc.body().html());
Run Code Online (Sandbox Code Playgroud)

输出:

<root>
 <newchild></newchild>
 <child></child>
 <child></child>
</root>
Run Code Online (Sandbox Code Playgroud)

要破译,它说:

  1. 选择根元素
  2. 抓住第一个根元素
  3. 抓住那个根元素的孩子
  4. 抓住第一个孩子
  5. 在该子项之前插入此元素


sha*_*hak 5

非常相似,使用prependElement()代替appendElement():

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