我的项目要求我采用如下格式的 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
编辑:要构建树,只需使用扫描仪继续阅读下一行。如果其中没有“/”,则将其推入堆栈。当您在一行中读取带有“/” ..()...的内容时,您将继续从堆栈中弹出,直到找到没有“/”的匹配标签 so 。弹出的所有内容都将作为兄弟姐妹连接,当您到达匹配标签的最后一个弹出窗口时,您将使其 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();
}
}