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