首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSoup元素与JSoup节点的区别

JSoup元素与JSoup节点的区别
EN

Stack Overflow用户
提问于 2017-12-19 15:22:08
回答 2查看 2.3K关注 0票数 9

谁能解释一下JSoup中提供的Element对象和Node对象之间的区别?

在哪种情况/条件下,哪种情况是最好的。

EN

回答 2

Stack Overflow用户

发布于 2017-12-19 16:25:27

节点是DOM层次结构中任何类型对象的通用名称。

元素是一种特定类型的节点。

JSoup类模型反映了这一点:

但是Element提供了额外的行为,使其更易于使用,例如,Element具有诸如idclass等属性,这使得在HTML文档中更容易找到它们。

在大多数情况下,使用Element (或Document的其他子类之一)可以满足您的需求,并且更易于编码。我怀疑您可能需要回退到Node的惟一场景是,如果DOM中有一个特定的节点类型,而JSoup没有为其提供Node的子类。

下面的示例显示了使用NodeElement检查相同的HTML文档

代码语言:javascript
复制
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"));
票数 10
EN

Stack Overflow用户

发布于 2021-11-03 06:22:55

看起来是一样的。但却不同。

节点有元素。另外还有TextNode。

所以..。举例说明。

代码语言:javascript
复制
<p>A<span>B</span></p>

在P元素中。

代码语言:javascript
复制
.childNodes() // get node list
-> A
-> <span>B</span>

.children() // get element list
-> <span>B</span>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47881838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档