more formatting.
[sfa.git] / util / rspec.py
1 import sys
2 import pprint
3 import os
4 from xml.dom import minidom
5 from types import StringTypes
6
7 class Rspec():
8
9     def __init__(self, xml = None, xsd = None):
10         self.xsd = xsd
11         self.rootNode = None
12         if xml:
13             self.parseString(xml)
14       
15   
16     def _getText(self, nodelist):
17         rc = ""
18         for node in nodelist:
19             if node.nodeType == node.TEXT_NODE:
20                 rc = rc + node.data
21         return rc
22   
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.
27   
28   
29     def _getName(self, node):
30         '''Gets name of node. If tag has no name, then return tag's localName'''
31         name = None
32         if not node.nodeName.startswith("#"):
33             if node.localName:
34                 name = node.localName
35             elif node.attributes.has_key("name"):
36                 name = node.attributes.get("name").value
37         return name     
38  
39  
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
46         return node
47   
48  
49     def toDict(self, nodeDom = None):
50         """
51         convert this rspec to a dict and return it.
52         """
53         node = {}
54         if not nodeDom:
55              nodeDom = self.rootNode
56   
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)
66                     if not childName:
67                         continue
68                     if not node[elementName].has_key(childName):
69                         node[elementName][childName] = []       
70                         #node[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))
75         return node
76
77   
78     def toxml(self):
79         """
80         convert this rspec to an xml string and return it.
81         """
82         return self.rootNode.toxml()
83
84   
85     def toprettyxml(self):
86         """
87         print this rspec in xml in a pretty format.
88         """
89         return self.rootNode.toprettyxml()
90
91   
92     def parseFile(self, filename):
93         """
94         read a local xml file and store it as a dom object.
95         """
96         dom = minidom.parse(filename)
97         self.rootNode = dom.childNodes[0]
98   
99   
100     def parseString(self, xml):
101         """
102         read an xml string and store it as a dom object.
103         """
104         xml = xml.replace('\n', '').replace('\t', '').strip()
105         dom = minidom.parseString(xml)
106         self.rootNode = dom.childNodes[0]
107
108  
109     def dict2dom(self, rdict, include_doc = False):
110         """
111         convert a dict object into a dom object.
112         """
113      
114     def elementNode(tagname, rd):
115         element = minidom.Element(tagname)   
116         for key in rd.keys():
117             if isinstance(rd[key], StringTypes):
118                 element.setAttribute(key, rd[key])
119             elif isinstance(rd[key], dict):
120                  child = elementNode(key, rd[key])
121                  element.appendChild(child)
122             elif isinstance(rd[key], list):
123                  for item in rd[key]:
124                      child = elementNode(key, item)
125                      element.appendChild(child)
126         return element
127                      
128         node = elementNode(rdict.keys()[0], rdict.values()[0])
129         if include_doc:
130             rootNode = minidom.Document()
131             rootNode.appendChild(node)
132         else:
133             rootNode = node
134         return rootNode
135
136  
137     def parseDict(self, rdict, include_doc = True):
138         """
139         Convert a dictionary into a dom object and store it.
140         """
141         self.rootNode = self.dict2dom(rdict, include_doc)
142  
143  
144     def getDictsByTagName(self, tagname, dom = None):
145         """
146         Search the dom for all elements with the specified tagname
147         and return them as a list of dicts
148         """
149         if not dom:
150             dom = self.rootNode
151         dicts = []
152         doms = dom.getElementsByTagName(tagname)
153         dictlist = [self.toDict(d) for d in doms]
154         for item in dictlist:
155             for value in item.values():
156                 dicts.append(value)
157         return dicts
158
159 # vim:ts=4:expandtab