簡體   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