2014-09-19 2 views
1

웹 문서에 대한 구조 분석을하고 있습니다. 이를 위해 웹 문서 (태그 만)의 구조 만 추출하면됩니다. Jsoup라는 자바 용 html 파서를 찾았습니다. 하지만 태그를 추출하는 방법을 모르겠습니다.Jsoup를 사용하여 html 파일에서 태그를 추출하십시오.

예 :

<html> 
<head> 
    this is head 
</head> 
<body> 
    this is body 
</body> 
</html> 

출력 :

public class JsoupDepthFirst { 

    private static String htmlTags(Document doc) { 
     StringBuilder sb = new StringBuilder(); 
     htmlTags(doc.children(), sb); 
     return sb.toString(); 
    } 

    private static void htmlTags(Elements elements, StringBuilder sb) { 
     for(Element el:elements) { 
      if(sb.length() > 0){ 
       sb.append(","); 
      } 
      sb.append(el.nodeName()); 
      htmlTags(el.children(), sb); 
      sb.append(",").append(el.nodeName()); 
     } 
    } 

    public static void main(String... args){ 
     String s = "<html><head>this is head </head><body>this is body</body></html>"; 
     Document doc = Jsoup.parse(s); 
     System.out.println(htmlTags(doc)); 
    } 
} 

다른 솔루션은 다음과 같이 NodeVisitor을 jsoup 사용하는 것이다 : 깊이 우선 탐색 등

html,head,head,body,body,html 
+0

(요소 엘 : doc.select ("*")) { \t에서 System.out.println (el.nodeName()); } 은 이미 분석 결과를 제공합니다. html, head, body 문서의 형식이 올바른 경우 태그 쌍을 얻습니다. –

답변

2

사운드

SecondSolution ss = new SecondSolution(); 
    doc.traverse(ss); 
    System.out.println(ss.sb.toString()); 

클래스 :

에 대한
public static class SecondSolution implements NodeVisitor { 

     StringBuilder sb = new StringBuilder(); 

     @Override 
     public void head(Node node, int depth) { 
      if (node instanceof Element && !(node instanceof Document)) { 
       if (sb.length() > 0) { 
        sb.append(","); 
       } 
       sb.append(node.nodeName()); 
      } 
     } 

     @Override 
     public void tail(Node node, int depth) { 
      if (node instanceof Element && !(node instanceof Document)) { 
       sb.append(",").append(node.nodeName()); 
      } 
     } 
    } 
+0

두 번째 것을 사용했습니다. 잘 작동합니다! thanks @ user1121883 –

관련 문제