4 from xml.dom import minidom
8 def __init__(self, xml = None, xsd = None):
12 self.parse_string(xml)
15 def _getText(self, nodelist):
18 if node.nodeType == node.TEXT_NODE:
22 # The rspec is comprised of 2 parts, and 1 reference:
23 # attributes/elements describe individual resources
24 # complexTypes are used to describe a set of attributes/elements
25 # complexTypes can include a reference to other complexTypes.
28 def _getName(self, node):
29 '''Gets name of node. If tag has no name, then return tag's localName'''
31 if not node.nodeName.startswith("#"):
34 elif node.attributes.has_key("name"):
35 name = node.attributes.get("name").value
39 # Attribute. {name : nameofattribute, {items: values})
40 def _attributeDict(self, attributeDom):
41 '''Traverse single attribute node. Create a dict {attributename : {name: value,}]}'''
42 node = {} # parsed dict
43 for attr in attributeDom.attributes.keys():
44 node[attr] = attributeDom.attributes.get(attr).value
48 def toDict(self, nodeDom = None):
50 convert this rspec to a dict and return it.
54 nodeDom = self.rootNode
56 elementName = nodeDom.nodeName
57 if elementName and not elementName.startswith("#"):
58 # attributes have tags and values. get {tag: value}, else {type: value}
59 node.update(self._attributeDict(nodeDom))
60 # resolve the child nodes.
61 if nodeDom.hasChildNodes():
62 for child in nodeDom.childNodes:
63 childName = self._getName(child)
66 if not node.has_key(childName):
68 node[childName].append(self.toDict2(child))
73 convert this rspec to an xml string and return it.
75 return self.rootNode.toxml()
77 def toprettyxml(self):
79 print this rspec in xml in a pretty format.
81 return self.rootNode.toprettyxml()
83 def parseFile(self, filename):
85 read a local xml file and store it as a dom object.
87 dom = minidom.parse(filename)
88 self.rootNode = dom.childNodes[0]
91 def parseString(self, xml):
93 read an xml string and store it as a dom object.
95 xml = xml.replace('\n', '').replace('\t', '').strip()
96 dom = minidom.parseString(xml)
97 self.rootNode = dom.childNodes[0]
99 def parseDict(self, d):
101 convert a dict object into a dom object.