节点是DOM层次结构中任何类型的对象的通用名称。
元素是节点的一种特定类型。
JSoup类模型反映了这一点:
由于Element extends Node您可以在上执行任何操作Node,因此您也可以执行Element。但是Element,它提供了其他行为,例如,使它更易于使用。一个Element具有如属性id和class等,这使得它更容易找到他们一个HTML文件内。
在大多数情况下,使用Element(或的其他子类之一Document)可以满足您的需求,并且更易于编码。我怀疑唯一可能需要回退的情况Node是DOM中是否存在特定的节点类型,而JSoup并未为其提供的子类Node。
这是一个示例,显示了同时使用Node和的相同HTML文档检查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"));
Run Code Online (Sandbox Code Playgroud)
YMMV,但我认为该Element表单更易于使用且出错的可能性小得多。
| 归档时间: |
|
| 查看次数: |
923 次 |
| 最近记录: |