【发布时间】:2018-06-01 14:03:02
【问题描述】:
谁能解释一下JSoup中提供的Element对象和Node对象的区别?
在哪种情况/条件下使用哪个是最好的。
【问题讨论】:
谁能解释一下JSoup中提供的Element对象和Node对象的区别?
在哪种情况/条件下使用哪个是最好的。
【问题讨论】:
好像是一样的。但不同。
节点有元素。并且还有 TextNode。
所以...例子。
<p>A<span>B</span></p>
在 P 元素中。
.childNodes() // get node list
-> A
-> <span>B</span>
.children() // get element list
-> <span>B</span>
【讨论】:
节点是 DOM 层次结构中任何类型对象的通用名称。
元素是一种特定类型的节点。
JSoup 类模型反映了这一点:
由于Element extends Node 可以在Node 上执行任何操作,因此您也可以在Element 上执行任何操作。但是Element 提供了额外的行为,使其更易于使用,例如; Element 具有 id 和 class 等属性,可以更轻松地在 HTML 文档中找到它们。
在大多数情况下,使用Element(或Document 的其他子类之一)将满足您的需求并且更容易编写代码。我怀疑您可能需要回退到 Node 的唯一情况是 DOM 中是否存在 JSoup 未为其提供 Node 子类的特定节点类型。
以下示例显示了使用 Node 和 Element 进行相同 HTML 文档检查:
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 表单更易于使用且不易出错。
【讨论】: