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);
}
}
}
}
scはスキャナで、htmlはそのようにフォーマットされています –