4 from xml.dom import minidom
5 from types import StringTypes
9 def __init__(self, xml = None, xsd = None):
13 self.parse_string(xml)
16 def _getText(self, nodelist):
19 if node.nodeType == node.TEXT_NODE:
23 # The rspec is comprised of 2 parts, and 1 reference:
24 # attributes/elements describe individual resources
25 # complexTypes are used to describe a set of attributes/elements
26 # complexTypes can include a reference to other complexTypes.
29 def _getName(self, node):
30 '''Gets name of node. If tag has no name, then return tag's localName'''
32 if not node.nodeName.startswith("#"):
35 elif node.attributes.has_key("name"):
36 name = node.attributes.get("name").value
40 # Attribute. {name : nameofattribute, {items: values})
41 def _attributeDict(self, attributeDom):
42 '''Traverse single attribute node. Create a dict {attributename : {name: value,}]}'''
43 node = {} # parsed dict
44 for attr in attributeDom.attributes.keys():
45 node[attr] = attributeDom.attributes.get(attr).value
49 def toDict(self, nodeDom = None):
51 convert this rspec to a dict and return it.
55 nodeDom = self.rootNode
57 elementName = nodeDom.nodeName
58 if elementName and not elementName.startswith("#"):
59 # attributes have tags and values. get {tag: value}, else {type: value}
60 node[elementName] = self._attributeDict(nodeDom)
61 #node.update(self._attributeDict(nodeDom))
62 # resolve the child nodes.
63 if nodeDom.hasChildNodes():
64 for child in nodeDom.childNodes:
65 childName = self._getName(child)
68 if not node[elementName].has_key(childName):
69 node[elementName][childName] = []
71 childdict = self.toDict(child)
72 for value in childdict.values():
73 node[elementName][childName].append(value)
74 #node[childName].append(self.toDict(child))
79 convert this rspec to an xml string and return it.
81 return self.rootNode.toxml()
83 def toprettyxml(self):
85 print this rspec in xml in a pretty format.
87 return self.rootNode.toprettyxml()
89 def parseFile(self, filename):
91 read a local xml file and store it as a dom object.
93 dom = minidom.parse(filename)
94 self.rootNode = dom.childNodes[0]
97 def parseString(self, xml):
99 read an xml string and store it as a dom object.
101 xml = xml.replace('\n', '').replace('\t', '').strip()
102 dom = minidom.parseString(xml)
103 self.rootNode = dom.childNodes[0]
105 def parseDict(self, rdict):
107 convert a dict object into a dom object.
109 doc = minidom.Document()
111 def elementNode(tagname, rd):
112 element = minidom.Element(tagname)
113 for key in rd.keys():
114 if isinstance(rd[key], StringTypes):
115 element.setAttribute(key, rd[key])
117 elif isinstance(rd[key], dict):
118 child = elementNode(key, rd[key])
119 element.appendChild(child)
121 elif isinstance(rd[key], list):
123 child = elementNode(key, item)
124 element.appendChild(child)
128 node = elementNode(rdict.keys()[0], rdict.values()[0])
129 doc.appendChild(node)