2012-03-29 4 views
0

Я пытаюсь построить дерево дерева, используя класс сканера в java, чтобы прочитать html. Ниже приведена моя реализация с использованием стека. по какой-то странной причине, когда я пытаюсь напечатать мое дерево только корень появляется и ничегосоздание дерева дерева чтение html с помощью java

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 отформатирован таким образом –

Смежные вопросы