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