The question is:
Implement XML
/HTML
Parser: essentially the same as the input is a tokenizer object, you can call its getNextToken()
function to get the next token, token structure including name and tag, name is a specific text, tag have open, close, text three kinds, let all the token to build a tree for example:
<html>
<user>
<id>aa</id>
<meta>bb</meta>
</user>
</html>
Tokens:
("html","open") ("user","open") ("id","open") ("aa","text") ("id","close")
("meta","open") ("bb","text") ("meta","close") ("user","close") ("html","close")
Implemented the following but am I understanding and answering the question correctly? And how can I implement it in Java?
class Node(object):
def __init__(self):
self.text = None
self.children = {}
class Solution(object):
def xmlParser(self, tokens):
root = Node()
s = [root]
for t in tokens:
print t
if t[1]=='open':
tmp = Node()
s[-1].children[t[0]] = tmp
s.append(tmp)
elif t[1]=='close':
s.pop()
elif t[1]=='text':
s[-1].text = t[0]
return root
Thank you in advance and will accept/upvote the answer