Parse XML tag content

This commit is contained in:
Némunaire 2012-06-30 16:38:39 +02:00
parent adc65ab84e
commit cf18e7c2e7
2 changed files with 22 additions and 0 deletions

View File

@ -10,6 +10,7 @@ class ModuleState:
def __init__(self, name):
self.name = name
self.content = ""
self.attributes = dict()
self.childs = list()
self.index = dict()
@ -80,6 +81,9 @@ class ModuleState:
"""DOM like method"""
self.attributes[name] = value
def getContent(self):
return self.content
def getChilds(self):
"""Return a full list of direct child of this node"""
return self.childs
@ -92,6 +96,13 @@ class ModuleState:
ret = child
return ret
def getFirstNode(self, tagname):
"""Get a unique node (or the last one) with the given tagname"""
for child in self.childs:
if tagname is None or tagname == child.name:
return child
return None
def getNodes(self, tagname):
"""Get all direct childs that have the given tagname"""
ret = list()

View File

@ -21,6 +21,9 @@ class ModuleStatesFile(xml.sax.ContentHandler):
self.stack.append(cur)
def characters(self, content):
self.stack[len(self.stack)-1].content += content
def endElement(self, name):
child = self.stack.pop()
size = len(self.stack)
@ -38,3 +41,11 @@ def parse_file(filename):
return mod.root
except:
return module_state.ModuleState("nemubotstate")
def parse_string(string):
mod = ModuleStatesFile()
try:
xml.sax.parseString(string, mod)
return mod.root
except:
return module_state.ModuleState("nemubotstate")