谁能解释一下JSoup中提供的Element对象和Node对象之间的区别?
在哪种情况/条件下,哪种情况是最好的。
发布于 2017-12-19 16:25:27
节点是DOM层次结构中任何类型对象的通用名称。
元素是一种特定类型的节点。
JSoup类模型反映了这一点:
但是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"));发布于 2021-11-03 06:22:55
看起来是一样的。但却不同。
节点有元素。另外还有TextNode。
所以..。举例说明。
<p>A<span>B</span></p>在P元素中。
.childNodes() // get node list
-> A
-> <span>B</span>
.children() // get element list
-> <span>B</span>https://stackoverflow.com/questions/47881838
复制相似问题