您好,我正在尝试在文档根元素中插入一个新的子元素,如下所示:
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>
为了破译,它说:
- 选择第一个根元素
- 获取该根元素上的第一个子元素
- 在那个 child 之前插入这个元素
您可以使用child
方法中的任何索引来选择任何 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>
关于java - 使用 Jsoup 在文档中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9942313/