2012-03-29 22 views
0

我想在java中使用掃描器類來構建dom樹來閱讀給html。以下是我使用堆棧的實現。因爲當我嘗試打印我的樹一些奇怪的原因只有根被顯示出來,並沒有別的建立一個dom樹使用java閱讀html

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,假設sc是一臺掃描儀,這可能或不是真的,對吧?

+0

sc是掃描儀html的格式是這樣的 – 2012-03-29 03:04:03