8 from xml.dom import minidom
9 from types import StringTypes, ListType
13 def __init__(self, xml = None, xsd = None, NSURL = None):
15 Class to manipulate RSpecs. Reads and parses rspec xml into python dicts
16 and reads python dicts and writes rspec xml
18 self.xsd = # Schema. Can be local or remote file.
19 self.NSURL = # If schema is remote, Name Space URL to query (full path minus filename)
20 self.rootNode = # root of the DOM
21 self.dict = # dict of the RSpec.
22 self.schemaDict = {} # dict of the Schema
35 self.dict = self.toDict()
37 self._parseXSD(self.NSURL + self.xsd)
40 def _getText(self, nodelist):
43 if node.nodeType == node.TEXT_NODE:
47 # The rspec is comprised of 2 parts, and 1 reference:
48 # attributes/elements describe individual resources
49 # complexTypes are used to describe a set of attributes/elements
50 # complexTypes can include a reference to other complexTypes.
53 def _getName(self, node):
54 '''Gets name of node. If tag has no name, then return tag's localName'''
56 if not node.nodeName.startswith("#"):
59 elif node.attributes.has_key("name"):
60 name = node.attributes.get("name").value
64 # Attribute. {name : nameofattribute, {items: values})
65 def _attributeDict(self, attributeDom):
66 '''Traverse single attribute node. Create a dict {attributename : {name: value,}]}'''
67 node = {} # parsed dict
68 for attr in attributeDom.attributes.keys():
69 node[attr] = attributeDom.attributes.get(attr).value
73 def appendToDictOrCreate(self, dict, key, value):
74 if (dict.has_key(key)):
75 dict[key].append(value)
80 def toGenDict(self, nodeDom=None, parentdict={}, siblingdict={}, parent=None):
82 convert an XML to a nested dict:
83 * Non-terminal nodes (elements with string children and attributes) are simple dictionaries
84 * Terminal nodes (the rest) are nested dictionaries
90 curNodeName = nodeDom.localName
92 if (nodeDom.nodeValue):
93 siblingdict = self.appendToDictOrCreate(siblingdict, parent, nodeDom.nodeValue)
94 elif (nodeDom.hasChildNodes()):
95 for child in nodeDom.childNodes:
96 siblingdict = self.toGenDict(child, None, siblingdict,curNodeName)
98 for attribute in nodeDom.attributes.keys():
99 parentdict = self.appendToDictOrCreate(parentdict, curNodeName, nodeDom.getAttribute(attribute))
101 if (parentdict is not None):
102 parentdict = self.appendToDictOrCreate(parentdict, curNodeName, siblingdict)
109 def toDict(self, nodeDom = None):
111 convert this rspec to a dict and return it.
115 nodeDom = self.rootNode
117 elementName = nodeDom.nodeName
118 if elementName and not elementName.startswith("#"):
119 # attributes have tags and values. get {tag: value}, else {type: value}
120 node[elementName] = self._attributeDict(nodeDom)
121 # resolve the child nodes.
122 if nodeDom.hasChildNodes():
123 for child in nodeDom.childNodes:
124 childName = self._getName(child)
128 # initialize the possible array of children
129 if not node[elementName].has_key(childName):
130 node[elementName][childName] = []
131 # if child node has text child nodes
132 # append the children to the array as strings
133 if child.hasChildNodes() and isinstance(child.childNodes[0], minidom.Text):
134 for nextchild in child.childNodes:
135 node[elementName][childName].append(nextchild.data)
136 # convert element child node to dict
138 childdict = self.toDict(child)
139 for value in childdict.values():
140 node[elementName][childName].append(value)
141 #node[childName].append(self.toDict(child))
147 convert this rspec to an xml string and return it.
149 return self.rootNode.toxml()
152 def toprettyxml(self):
154 print this rspec in xml in a pretty format.
156 return self.rootNode.toprettyxml()
159 def parseFile(self, filename):
161 read a local xml file and store it as a dom object.
163 dom = minidom.parse(filename)
164 self.rootNode = dom.childNodes[0]
167 def parseString(self, xml):
169 read an xml string and store it as a dom object.
171 xml = xml.replace('\n', '').replace('\t', '').replace(' ', '').strip()
172 dom = minidom.parseString(xml)
173 self.rootNode = dom.childNodes[0]
176 def _httpGetXSD(self, xsdURI):
177 # split the URI into relevant parts
178 host = xsdURI.split("/")[2]
179 if xsdURI.startswith("https"):
180 conn = httplib.HTTPSConnection(host,
181 httplib.HTTPSConnection.default_port)
182 elif xsdURI.startswith("http"):
183 conn = httplib.HTTPConnection(host,
184 httplib.HTTPConnection.default_port)
185 conn.request("GET", xsdURI)
186 # If we can't download the schema, raise an exception
187 r1 = conn.getresponse()
190 return r1.read().replace('\n', '').replace('\t', '').strip()
193 def _parseXSD(self, xsdURI):
195 Download XSD from URL, or if file, read local xsd file and set schemaDict
197 # Since the schema definiton is a global namespace shared by and agreed upon by
198 # others, this should probably be a URL. Check for URL, download xsd, parse, or
199 # if local file, use local file.
201 if xsdURI.startswith("http"):
203 schemaDom = minidom.parseString(self._httpGetXSD(xsdURI))
205 # logging.debug("%s: web file not found" % xsdURI)
206 # logging.debug("Using local file %s" % self.xsd")
208 print "Can't find %s on the web. Continuing." % xsdURI
210 if os.path.exists(xsdURI):
211 # logging.debug("using local copy.")
212 print "Using local %s" % xsdURI
213 schemaDom = minidom.parse(xsdURI)
215 raise Exception("Can't find xsd locally")
216 self.schemaDict = self.toDict(schemaDom.childNodes[0])
219 def dict2dom(self, rdict, include_doc = False):
221 convert a dict object into a dom object.
224 def elementNode(tagname, rd):
225 element = minidom.Element(tagname)
226 for key in rd.keys():
227 if isinstance(rd[key], StringTypes) or isinstance(rd[key], int):
228 element.setAttribute(key, str(rd[key]))
229 elif isinstance(rd[key], dict):
230 child = elementNode(key, rd[key])
231 element.appendChild(child)
232 elif isinstance(rd[key], list):
234 if isinstance(item, dict):
235 child = elementNode(key, item)
236 element.appendChild(child)
237 elif isinstance(item, StringTypes) or isinstance(item, int):
238 child = minidom.Element(key)
239 text = minidom.Text()
241 child.appendChild(text)
242 element.appendChild(child)
245 # Minidom does not allow documents to have more then one
246 # child, but elements may have many children. Because of
247 # this, the document's root node will be the first key/value
248 # pair in the dictionary.
249 node = elementNode(rdict.keys()[0], rdict.values()[0])
251 rootNode = minidom.Document()
252 rootNode.appendChild(node)
258 def parseDict(self, rdict, include_doc = True):
260 Convert a dictionary into a dom object and store it.
262 self.rootNode = self.dict2dom(rdict, include_doc)
265 def getDictsByTagName(self, tagname, dom = None):
267 Search the dom for all elements with the specified tagname
268 and return them as a list of dicts
273 doms = dom.getElementsByTagName(tagname)
274 dictlist = [self.toDict(d) for d in doms]
275 for item in dictlist:
276 for value in item.values():
280 def getDictByTagNameValue(self, tagname, value, dom = None):
282 Search the dom for the first element with the specified tagname
283 and value and return it as a dict.
288 dicts = self.getDictsByTagName(tagname, dom)
291 if rdict.has_key('name') and rdict['name'] in [value]:
297 def filter(self, tagname, attribute, blacklist = [], whitelist = [], dom = None):
299 Removes all elements where:
300 1. tagname matches the element tag
301 2. attribute matches the element attribte
302 3. attribute value is in valuelist
309 if dom.localName in [tagname] and dom.attributes.has_key(attribute):
310 if whitelist and dom.attributes.get(attribute).value not in whitelist:
311 dom.parentNode.removeChild(dom)
312 if blacklist and dom.attributes.get(attribute).value in blacklist:
313 dom.parentNode.removeChild(dom)
315 if dom.hasChildNodes():
316 for child in dom.childNodes:
317 self.filter(tagname, attribute, blacklist, whitelist, child)
320 def validateDicts(self):
330 def pprint(self, r = None, depth = 0):
332 Pretty print the dict
335 if r == None: r = self.dict
337 for tab in range(0,depth): line += " "
338 # check if it's nested
341 print line + "%s:" % i
342 self.pprint(r[i], depth + 1)
343 elif type(r) in (tuple, list):
344 for j in r: self.pprint(j, depth + 1)
345 # not nested so just print.
347 print line + "%s" % r
351 class RecordSpec(Rspec):
354 def parseDict(self, rdict, include_doc = False):
356 Convert a dictionary into a dom object and store it.
358 self.rootNode = self.dict2dom(rdict, include_doc)
360 def dict2dom(self, rdict, include_doc = False):
362 if not len(rdict.keys()) == 1:
363 record_dict = {self.root_tag : rdict}
364 return Rspec.dict2dom(self, record_dict, include_doc)