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