[英]How to parse an HTML document for an element list of 'tagname' using 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>
为了破译,它说:
您可以使用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.