java 使用 Jsoup 在文档中插入元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9942313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:59:40  来源:igfitidea点击:

Inserting Element in a Document using Jsoup

javaparsingjsoup

提问by B. Anderson

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>

回答by B. Anderson

See if this helps you out:

看看这是否对你有帮助:

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

Output:

输出:

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

To decipher, it says:

为了破译,它说:

  1. Select the root elements
  2. Grab the first root element
  3. Grab the children on that root element
  4. Grab the first child
  5. Before that child insert this element
  1. 选择根元素
  2. 获取第一个根元素
  3. 抓住那个根元素上的孩子
  4. 抓住第一个孩子
  5. 在那个孩子之前插入这个元素

回答by shak

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