2017-12-19 12 views

答えて

4

ノードは、DOM階層内の任意のタイプのオブジェクトの総称です。

要素は、1つの特定のタイプのノードです。

JSoupクラスモデル

はこれを反映して:あなたは Node上で行うことができます

Element extends Nodeので、あなたもElement上で行うことができます。しかし、Elementは、たとえば使いやすくするための追加の動作を提供します。 は、idclassなどのプロパティを持ち、HTMLドキュメントでそれらを簡単に見つけることができます。 Element(またはDocumentの他のサブクラスの1)を使用して、ほとんどのケースで

はあなたのニーズを満たすだろうとにコーディングする容易になります。私はNodeに戻る必要がある唯一のシナリオは、JSoupがNodeというサブクラスを提供しない特定のノードタイプがDOM内にある場合です。

はここNodeElementの両方を使用して、同じ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フォームが発生しやすい使いやすくしてはるかに少ない誤りだと思います。