47de319c8a023527ddd05abefdf34d3bd0fc7b61
[sfa.git] / sfa / util / xml.py
1 #!/usr/bin/python 
2 from types import StringTypes
3 from lxml import etree
4 from StringIO import StringIO
5 from sfa.util.faults import InvalidXML
6
7 class XpathFilter:
8     @staticmethod
9
10     def filter_value(key, value):
11         xpath = ""    
12         if isinstance(value, str):
13             if '*' in value:
14                 value = value.replace('*', '')
15                 xpath = 'contains(%s, "%s")' % (key, value)
16             else:
17                 xpath = '%s="%s"' % (key, value)                
18         return xpath
19
20     @staticmethod
21     def xpath(filter={}):
22         xpath = ""
23         if filter:
24             filter_list = []
25             for (key, value) in filter.items():
26                 if key == 'text':
27                     key = 'text()'
28                 else:
29                     key = '@'+key
30                 if isinstance(value, str):
31                     filter_list.append(XpathFilter.filter_value(key, value))
32                 elif isinstance(value, list):
33                     stmt = ' or '.join([XpathFilter.filter_value(key, str(val)) for val in value])
34                     filter_list.append(stmt)   
35             if filter_list:
36                 xpath = ' and '.join(filter_list)
37                 xpath = '[' + xpath + ']'
38         return xpath
39
40 class XmlNode:
41     def __init__(self, node, namespaces):
42         self.node = node
43         self.text = node.text
44         self.namespaces = namespaces
45         self.attrib = node.attrib
46         
47
48     def xpath(self, xpath, namespaces=None):
49         if not namespaces:
50             namespaces = self.namespaces 
51         elems = self.node.xpath(xpath, namespaces=namespaces)
52         return [XmlNode(elem, namespaces) for elem in elems]
53     
54     def add_element(name, *args, **kwds):
55         element = etree.SubElement(name, args, kwds)
56         return XmlNode(element, self.namespaces)
57
58     def remove_elements(name):
59         """
60         Removes all occurences of an element from the tree. Start at
61         specified root_node if specified, otherwise start at tree's root.
62         """
63         
64         if not element_name.startswith('//'):
65             element_name = '//' + element_name
66         elements = self.node.xpath('%s ' % name, namespaces=self.namespaces) 
67         for element in elements:
68             parent = element.getparent()
69             parent.remove(element)
70
71     def remove(element):
72         self.node.remove(element)
73
74     def set(self, key, value):
75         self.node.set(key, value)
76     
77     def set_text(self, text):
78         self.node.text = text
79     
80     def unset(self, key):
81         del self.node.attrib[key]
82   
83     def iterchildren(self):
84         return self.node.iterchildren()
85      
86     def toxml(self):
87         return etree.tostring(self.node, encoding='UTF-8', pretty_print=True)                    
88
89     def __str__(self):
90         return self.toxml()
91
92 class XML:
93  
94     def __init__(self, xml=None, namespaces=None):
95         self.root = None
96         self.namespaces = namespaces
97         self.default_namespace = None
98         self.schema = None
99         if isinstance(xml, basestring):
100             self.parse_xml(xml)
101         if isinstance(xml, XmlNode):
102             self.root = xml
103             self.namespaces = xml.namespaces
104         elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
105             self.parse_xml(etree.tostring(xml))
106
107     def parse_xml(self, xml):
108         """
109         parse rspec into etree
110         """
111         parser = etree.XMLParser(remove_blank_text=True)
112         try:
113             tree = etree.parse(xml, parser)
114         except IOError:
115             # 'rspec' file doesnt exist. 'rspec' is proably an xml string
116             try:
117                 tree = etree.parse(StringIO(xml), parser)
118             except Exception, e:
119                 raise InvalidXML(str(e))
120         root = tree.getroot()
121         self.namespaces = dict(root.nsmap)
122         # set namespaces map
123         if 'default' not in self.namespaces and None in self.namespaces: 
124             # If the 'None' exist, then it's pointing to the default namespace. This makes 
125             # it hard for us to write xpath queries for the default naemspace because lxml 
126             # wont understand a None prefix. We will just associate the default namespeace 
127             # with a key named 'default'.     
128             self.namespaces['default'] = self.namespaces.pop(None)
129             
130         else:
131             self.namespaces['default'] = 'default' 
132
133         self.root = XmlNode(root, self.namespaces)
134         # set schema 
135         for key in self.root.attrib.keys():
136             if key.endswith('schemaLocation'):
137                 # schema location should be at the end of the list
138                 schema_parts  = self.root.attrib[key].split(' ')
139                 self.schema = schema_parts[1]    
140                 namespace, schema  = schema_parts[0], schema_parts[1]
141                 break
142
143     def parse_dict(self, d, root_tag_name='xml', element = None):
144         if element is None: 
145             if self.root is None:
146                 self.parse_xml('<%s/>' % root_tag_name)
147             element = self.root
148
149         if 'text' in d:
150             text = d.pop('text')
151             element.text = text
152
153         # handle repeating fields
154         for (key, value) in d.items():
155             if isinstance(value, list):
156                 value = d.pop(key)
157                 for val in value:
158                     if isinstance(val, dict):
159                         child_element = etree.SubElement(element, key)
160                         self.parse_dict(val, key, child_element)
161                     elif isinstance(val, basestring):
162                         child_element = etree.SubElement(element, key).text = val
163                         
164             elif isinstance(value, int):
165                 d[key] = unicode(d[key])  
166             elif value is None:
167                 d.pop(key)
168
169         # element.attrib.update will explode if DateTimes are in the
170         # dcitionary.
171         d=d.copy()
172         # looks like iteritems won't stand side-effects
173         for k in d.keys():
174             if not isinstance(d[k],StringTypes):
175                 del d[k]
176
177         element.attrib.update(d)
178
179     def validate(self, schema):
180         """
181         Validate against rng schema
182         """
183         relaxng_doc = etree.parse(schema)
184         relaxng = etree.RelaxNG(relaxng_doc)
185         if not relaxng(self.root):
186             error = relaxng.error_log.last_error
187             message = "%s (line %s)" % (error.message, error.line)
188             raise InvalidXML(message)
189         return True
190
191     def xpath(self, xpath, namespaces=None):
192         if not namespaces:
193             namespaces = self.namespaces
194         return self.root.xpath(xpath, namespaces=namespaces)
195
196     def set(self, key, value, node=None):
197         if not node:
198             node = self.root 
199         return node.set(key, value)
200
201     def remove_attribute(self, name, node=None):
202         if not node:
203             node = self.root
204         node.remove_attribute(name) 
205         
206
207     def add_element(self, name, attrs={}, parent=None, text=""):
208         """
209         Wrapper around etree.SubElement(). Adds an element to 
210         specified parent node. Adds element to root node is parent is 
211         not specified. 
212         """
213         if parent == None:
214             parent = self.root
215         element = etree.SubElement(parent, name)
216         if text:
217             element.text = text
218         if isinstance(attrs, dict):
219             for attr in attrs:
220                 element.set(attr, attrs[attr])  
221         return XmlNode(element, self.namespaces)
222
223     def remove_elements(self, name, node = None):
224         """
225         Removes all occurences of an element from the tree. Start at 
226         specified root_node if specified, otherwise start at tree's root.   
227         """
228         if not node:
229             node = self.root
230
231         node.remove_elements(name)
232
233     def attributes_list(self, elem):
234         # convert a list of attribute tags into list of tuples
235         # (tagnme, text_value)
236         opts = []
237         if elem is not None:
238             for e in elem:
239                 opts.append((e.tag, str(e.text).strip()))
240         return opts
241
242     def get_element_attributes(self, elem=None, depth=0):
243         if elem == None:
244             elem = self.root_node
245         if not hasattr(elem, 'attrib'):
246             # this is probably not an element node with attribute. could be just and an
247             # attribute, return it
248             return elem
249         attrs = dict(elem.attrib)
250         attrs['text'] = str(elem.text).strip()
251         attrs['parent'] = elem.getparent()
252         if isinstance(depth, int) and depth > 0:
253             for child_elem in list(elem):
254                 key = str(child_elem.tag)
255                 if key not in attrs:
256                     attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
257                 else:
258                     attrs[key].append(self.get_element_attributes(child_elem, depth-1))
259         else:
260             attrs['child_nodes'] = list(elem)
261         return attrs
262
263     def merge(self, in_xml):
264         pass
265
266     def __str__(self):
267         return self.toxml()
268
269     def toxml(self):
270         return etree.tostring(self.root, encoding='UTF-8', pretty_print=True)  
271     
272     # XXX smbaker, for record.load_from_string
273     def todict(self, elem=None):
274         if elem is None:
275             elem = self.root
276         d = {}
277         d.update(elem.attrib)
278         d['text'] = elem.text
279         for child in elem.iterchildren():
280             if child.tag not in d:
281                 d[child.tag] = []
282             d[child.tag].append(self.todict(child))
283
284         if len(d)==1 and ("text" in d):
285             d = d["text"]
286
287         return d
288         
289     def save(self, filename):
290         f = open(filename, 'w')
291         f.write(self.toxml())
292         f.close()
293
294 # no RSpec in scope 
295 #if __name__ == '__main__':
296 #    rspec = RSpec('/tmp/resources.rspec')
297 #    print rspec
298