JSoup元素和JSoup节点之间的区别 [英] Difference between JSoup Element and JSoup Node
问题描述
任何人都可以解释JSoup中提供的Element
对象和Node
对象之间的区别吗?
Can anyone please explain the difference between the Element
object and Node
object provided in JSoup ?
在哪种情况/条件下最好使用哪种?
Which is the best thing to be used in which situation/condition.
推荐答案
节点是DOM层次结构中任何类型的对象的通用名称.
A node is the generic name for any type of object in the DOM hierarchy.
元素是节点的一种特定类型.
An element is one specific type of node.
JSoup类模型反映了这一点:
The JSoup class model reflects this:
- Node
- Element
由于Element extends Node
可以在Node
上执行的任何操作,所以您也可以在Element
上执行.但是Element
提供了其他行为,例如,它更易于使用. Element
具有诸如id
和class
等的属性,这些属性使在HTML文档中更容易找到它们.
Since Element extends Node
anything you can do on a Node
, you can do on an Element
too. But Element
provides additional behaviour which makes it easier to use, for example; an Element
has properties such as id
and class
etc which make it easier to find them in a HTML document.
在大多数情况下,使用Element
(或Document
的其他子类之一)将满足您的需求,并且更容易进行编码.我怀疑唯一可能需要退回到Node
的情况是DOM中是否存在特定的节点类型,而JSoup并未为其提供Node
的子类.
In most cases using Element
(or one of the other subclasses of Document
) will meet your needs and will be easier to code to. I suspect the only scenario in which you might need to fall back to Node
is if there is a specific node type in the DOM for which JSoup does not provide a subclass of Node
.
下面的示例显示了同时使用Node
和Element
进行的HTML文档检查:
Here's an example showing the same HTML document inspection using both Node
and Element
:
String html = "<html><head><title>This is the head</title></head><body><p>This is the body</p></body></html>";
Document doc = Jsoup.parse(html);
Node root = doc.root();
// some content assertions, using Node
assertThat(root.childNodes().size(), is(1));
assertThat(root.childNode(0).childNodes().size(), is(2));
assertThat(root.childNode(0).childNode(0), instanceOf(Element.class));
assertThat(((Element) root.childNode(0).childNode(0)).text(), is("This is the head"));
assertThat(root.childNode(0).childNode(1), instanceOf(Element.class));
assertThat(((Element) root.childNode(0).childNode(1)).text(), is("This is the body"));
// the same content assertions, using Element
Elements head = doc.getElementsByTag("head");
assertThat(head.size(), is(1));
assertThat(head.first().text(), is("This is the head"));
Elements body = doc.getElementsByTag("body");
assertThat(body.size(), is(1));
assertThat(body.first().text(), is("This is the body"));
YMMV,但我认为Element
表单更易于使用,更不容易出错.
YMMV but I think the Element
form is easier to use and much less error prone.
这篇关于JSoup元素和JSoup节点之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!