使用Jsoup删除元素不起作用 [英] Removing Element with Jsoup doesn't work
问题描述
我想删除html文件头部的一些元素(CSS - 标签)。
我试过这样:
i want to remove some elements (CSS--tags) in the head of a html file. I tried it like this:
Document doc = Jsoup.parse(htmlString);
Element head = doc.head();
Elements headChildren = head.children();
for (Element el : headChildren) {
if (el.attr("type").contains("text/css") || el.attr("rel").contains("stylesheet")){
Log.d("HTML", "elements-before: " + el.nodeName()); //Log prints 7 elments
el.remove();
}
}
for (Element el : headChildren ) {
if (el.attr("type").contains("text/css") || el.attr("rel").contains("stylesheet")){
Log.d("HTML", "elements-after: " + el.nodeName()); //Log prints 7 elments again
}
}
知道我的错误在哪里。
I really don't know where my fault is. Please help me out.
推荐答案
请帮助我。
您要从它们所在的文档
对象中删除元素
,而不是 Elements
集合。因此,当您第二次打印每个 Element
时,它们仍然在 Elements
集合中, code> 。
You are removing the Element
from the Document
object where they are located, not the Elements
collection. Thus, when you print each Element
the second time, they are still in the Elements
collection, but not in the Document
.
Jsoup类 Element
,注释
,文档
等都是Node类的所有子类,它表示DOM树中的一个节点。方法 remove()
是从 Node
类继承的方法,它从DOM树中删除节点。
The Jsoup classes Element
, Comment
, Document
and so on are all subclasses of the Node class, which represents a node in the DOM tree. The method remove()
is an inherited method from the Node
class, and it removes the node from the DOM tree.
这篇关于使用Jsoup删除元素不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!