누구나 Element
개체와 Node
개체가 JSoup에서 제공된다는 차이점을 설명해 주실 수 있습니까?JSoup 요소와 JSoup 노드의 차이점
어떤 상황/조건에서 사용하는 것이 가장 좋습니다.
누구나 Element
개체와 Node
개체가 JSoup에서 제공된다는 차이점을 설명해 주실 수 있습니까?JSoup 요소와 JSoup 노드의 차이점
어떤 상황/조건에서 사용하는 것이 가장 좋습니다.
노드는 DOM 계층의 모든 유형의 객체에 대한 일반 이름입니다.
요소는 특정 유형의 노드입니다.
JSoup 클래스 모델
이 반영 : 당신이Node
에 할 수있는
아무것도 Element extends Node
때문에, 당신이 너무 Element
에 할 수 있습니다. 그러나 Element
은 사용하기 쉬운 추가 동작을 제공합니다 (예 : Element
은 id
및 class
과 같은 속성을 가지고있어 HTML 문서에서 쉽게 찾을 수 있습니다. 당신의 필요를 충족하고 쉽게가 코딩하는 것 Element
(또는 Document
의 다른 서브 클래스 중 하나)를 사용하여 대부분의 경우
. 나는 Node
으로 돌아갈 필요가있는 유일한 시나리오는 DOM에 특정 노드 유형이있는 경우 JS0p가 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"));
YMMV을하지만 난 Element
형태는 사용하기 쉽고 더 적은 오류가 발생하기 쉬운 생각합니다.