您好我正在尝试在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)
要破译,它说:
非常相似,使用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)
| 归档时间: |
|
| 查看次数: |
14021 次 |
| 最近记录: |