你问为什么这不起作用
elements.get(1).remove();
// remove doesn't affect elements. why?
答案可以在实现中找到。
您在元素上调用的方法是在
Node 类。
public void remove() {
Validate.notNull(this.parentNode);
this.parentNode.removeChild(this);
}
如您所见,调用 remove() 从父元素中删除了此元素
(如果您打印文档,您将看到元素 b 已
删除。但这并不意味着已从列表中删除
Elements 类拥有的元素。
public class Elements implements List<Element>, Cloneable {
private List<Element> contents;
为了做到这一点,你必须按照@Silviu Burcea 向你展示的方式去做,
通过调用方法remove(int index),您正在调用以下方法
可以在Elements 类中找到实现
public Element remove(int index) {
return ((Element) this.contents.remove(index));
}
虽然心里很清楚,但如果你这样做,你唯一要做的就是
从Elements 类包含的列表中删除第 i 个元素。
查看这些示例
示例1:元素的大小减小了,但文档保持不变
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class Main {
public static void main(String[] args) throws Exception {
String baseHtml = "<div>a</div>" +
"<div>b</div>" +
"<div>c</div>";
Document doc = Jsoup.parse(baseHtml);
Elements elements = doc.select("div");
elements.remove(1);
System.out.println(doc.outerHtml());
System.out.println("-----------------------------------");
System.out.println(elements.size());
System.out.println("-----------------------------------");
System.out.println(doc.outerHtml());
}
}
示例 2:元素保持不变,但文档发生了变化
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class Main {
public static void main(String[] args) throws Exception {
String baseHtml = "<div>a</div>" +
"<div>b</div>" +
"<div>c</div>";
Document doc = Jsoup.parse(baseHtml);
Elements elements = doc.select("div");
elements.get(1).remove();
System.out.println(doc.outerHtml());
System.out.println("-----------------------------------");
System.out.println(elements.size());
System.out.println("-----------------------------------");
System.out.println(doc.outerHtml());
}
}
我希望这有助于消除混乱。