JSoup元素和JSoup节点之间的区别 [英] Difference between JSoup Element and JSoup Node

查看:54
本文介绍了JSoup元素和JSoup节点之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释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具有诸如idclass等的属性,这些属性使在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.

下面的示例显示了同时使用NodeElement进行的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆