从html构建(二叉树)DOM树

时间:2013-11-07 21:54:33

标签: java binary-tree

我的项目要求我采用如下格式的HTML代码:

<html>
<body>
The 
<b>
quick
</b>
 brown fox
</body>
</html>

从这里开始,我必须制作一个这样的DOM树:

   ----------
    |html| |\|
    ------|---
          |
          V
       ----------
       |body| |\|
       ------|---
             |
             V
          ----------   -------   ----------------
          |The |\|-|-> |b| |-|-> | brown fox|\|\|
          ----------   ---|---   ----------------
                          |
                          V
                       -----------
                       |quick|\|\|
                       -----------

我想要使用堆栈或递归,但我不确定哪种方法最好。对我来说,这看起来像一棵二叉树,左边的树是儿童,右边的树是兄弟姐妹。看起来如果前一个节点是文本,则当前节点成为兄弟节点。细分的代码可能如下所示:

<html> -root
 <body> -child
  The -child
  <b> -sibling
   quick -child
  </b> -return
  brown fox -sibling
 </body
<html

编辑: 要构建树,只需继续使用扫描仪读取下一行。如果它没有“/”,则将其推入堆栈。当你用“/”..()...读取一行时,你将继续从堆栈中弹出,直到找到没有“/”的匹配标记。弹出的所有东西都将作为兄弟姐妹连接,当你到达最终的pop是匹配的标签时,你将把它的firstChild作为最后一个弹出的标签。

public void build() {
    Stack<TagNode> tags = new Stack<TagNode>();
    Stack<TagNode> reverse = new Stack<TagNode>();

    while(sc.hasNext()){
        String curr = sc.nextLine();

        if(!curr.contains("/")){ //is an open tag or text, push it
            tags.push(new TagNode(curr,null,null));
        }else{ //is a closing tag
            TagNode base = tags.pop();
            while(tags.peek().tag.equals(curr.replaceFirst("/", ""))){ //while we haven't hit the opening tag yet, take the first node, then add everything else as siblings
                TagNode temp = tags.pop();
                temp.sibling = base;
                base = temp;
            }
            tags.peek().firstChild = base;
            root = tags.peek();
        }
}

0 个答案:

没有答案
相关问题