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