2017-12-19 22 views

답변

4

노드는 DOM 계층의 모든 유형의 객체에 대한 일반 이름입니다.

요소는 특정 유형의 노드입니다.

JSoup 클래스 모델

이 반영 : 당신이 Node에 할 수있는

아무것도 Element extends Node 때문에, 당신이 너무 Element에 할 수 있습니다. 그러나 Element은 사용하기 쉬운 추가 동작을 제공합니다 (예 : Elementidclass과 같은 속성을 가지고있어 HTML 문서에서 쉽게 찾을 수 있습니다. 당신의 필요를 충족하고 쉽게가 코딩하는 것 Element (또는 Document의 다른 서브 클래스 중 하나)를 사용하여 대부분의 경우

. 나는 Node으로 돌아갈 필요가있는 유일한 시나리오는 DOM에 특정 노드 유형이있는 경우 JS0p가 Node의 서브 클래스를 제공하지 않는다는 것입니다.

는 여기에 모두 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 형태는 사용하기 쉽고 더 적은 오류가 발생하기 쉬운 생각합니다.