![](/img/trans.png)
[英]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.