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