2012-03-29 8 views
0

私は与えられたhtmlを読むためにjavaのscannerクラスを使ってdomツリーを構築しようとしています。以下はスタックを使った私の実装です。私は私の木を印刷しようといくつかの奇妙な理由で唯一のルートがアップし、他には何も表示されjavaを使用してhtmlを読むdomツリーを構築する

public void build() { 

     root = new TagNode("", null, null); 
     TagNode ptr = null; 

     Stack<TagNode> tags = new Stack<TagNode>(); 

     while (sc.hasNextLine()) { 

      String tag = sc.nextLine(); 

      if (tag.equals("<html>")) { 

       ptr = new TagNode("html", null, null); 
       tags.push(ptr); 
       root.tag = "html"; 

      } 

      else if (tag.charAt(0) == '<') { 

       if (tag.charAt(1) == '/') { 

        tags.pop(); 
        continue; 

       } 

       else if (tags.peek().firstChild == null) { 

        String temp = tag.replaceAll("<", ""); 
        temp = temp.replaceAll(">", ""); 
        ptr = new TagNode(temp, null, null); 
        tags.peek().firstChild = ptr; 
        tags.push(ptr); 

       } 

       else { 

        TagNode temp = tags.peek().firstChild; 

        while (temp.sibling != null) { 

         temp = temp.sibling; 

        } 

        String a = tag.replaceAll("<", ""); 
        a = a.replaceAll(">", ""); 
        ptr = new TagNode(a, null, null); 

        temp.sibling = ptr; 
        tags.push(ptr); 

       } 

      } 

      else { 

       if (tags.peek().firstChild == null) { 

        tags.peek().firstChild = new TagNode(tag, null, null); 

       } 

       else { 

        TagNode temp = tags.peek().firstChild; 

        while (temp.sibling != null) { 

         temp = temp.sibling; 

        } 

        temp.sibling = new TagNode(tag, null, null); 

       } 
      }  
     }   

    } 

答えて

0

あなたの例では不完全であるが、それを見ているから、私は問題が


while (sc.hasNextLine()) { 
     String tag = sc.nextLine(); 
であると思います

あなたはタグが行の先頭に来ると仮定しています。あなたのHTMLとスキャナがスキャナであると仮定すると、どちらが真実かもしれません。

+0

scはスキャナで、htmlはそのようにフォーマットされています –

関連する問題