2 from types import StringTypes
4 from StringIO import StringIO
5 from sfa.util.faults import InvalidXML
6 from sfa.rspecs.elements.element import Element
8 # helper functions to help build xpaths
12 def filter_value(key, value):
14 if isinstance(value, str):
16 value = value.replace('*', '')
17 xpath = 'contains(%s, "%s")' % (key, value)
19 xpath = '%s="%s"' % (key, value)
27 for (key, value) in filter.items():
32 if isinstance(value, str):
33 filter_list.append(XpathFilter.filter_value(key, value))
34 elif isinstance(value, list):
35 stmt = ' or '.join([XpathFilter.filter_value(key, str(val)) for val in value])
36 filter_list.append(stmt)
38 xpath = ' and '.join(filter_list)
39 xpath = '[' + xpath + ']'
42 # a wrapper class around lxml.etree._Element
43 # the reason why we need this one is because of the limitations
44 # we've found in xpath to address documents with multiple namespaces defined
45 # in a nutshell, we deal with xml documents that have
46 # a default namespace defined (xmlns="http://default.com/") and specific prefixes defined
47 # (xmlns:foo="http://foo.com")
48 # according to the documentation instead of writing
49 # element.xpath ( "//node/foo:subnode" )
50 # we'd then need to write xpaths like
51 # element.xpath ( "//{http://default.com/}node/{http://foo.com}subnode" )
52 # which is a real pain..
53 # So just so we can keep some reasonable programming style we need to manage the
54 # namespace map that goes with the _Element (its internal .nsmap being unmutable)
57 def __init__(self, element, namespaces):
58 self.element = element
59 self.namespaces = namespaces
61 # redefine as few methods as possible
62 def xpath(self, xpath, namespaces=None):
64 namespaces = self.namespaces
65 elems = self.element.xpath(xpath, namespaces=namespaces)
66 return [XmlElement(elem, namespaces) for elem in elems]
68 def add_element(self, tagname, **kwds):
69 element = etree.SubElement(self.element, tagname, **kwds)
70 return XmlElement(element, self.namespaces)
72 def append(self, elem):
73 if isinstance(elem, XmlElement):
74 self.element.append(elem.element)
76 self.element.append(elem)
79 return XmlElement(self.element.getparent(), self.namespaces)
81 def get_instance(self, instance_class=None, fields=[]):
83 Returns an instance (dict) of this xml element. The instance
84 holds a reference to this xml element.
86 if not instance_class:
87 instance_class = Element
88 if not fields and hasattr(instance_class, 'fields'):
89 fields = instance_class.fields
92 instance = instance_class(self.attrib, self)
94 instance = instance_class({}, self)
96 if field in self.attrib:
97 instance[field] = self.attrib[field]
100 def add_instance(self, name, instance, fields=[]):
102 Adds the specifed instance(s) as a child element of this xml
105 if not fields and hasattr(instance, 'keys'):
106 fields = instance.keys()
107 elem = self.add_element(name)
109 if field in instance and instance[field]:
110 elem.set(field, unicode(instance[field]))
113 def remove_elements(self, name):
115 Removes all occurences of an element from the tree. Start at
116 specified root_node if specified, otherwise start at tree's root.
119 if not element_name.startswith('//'):
120 element_name = '//' + element_name
121 elements = self.element.xpath('%s ' % name, namespaces=self.namespaces)
122 for element in elements:
123 parent = element.getparent()
124 parent.remove(element)
127 parent = self.getparent()
130 def remove(self, element):
131 if isinstance(element, XmlElement):
132 self.element.remove(element.element)
134 self.element.remove(element)
136 def set_text(self, text):
137 self.element.text = text
139 # Element does not have unset ?!?
140 def unset(self, key):
141 del self.element.attrib[key]
144 return etree.tostring(self.element, encoding='UTF-8', pretty_print=True)
149 ### other method calls or attribute access like .text or .tag or .get
150 # are redirected on self.element
151 def __getattr__ (self, name):
152 if not hasattr(self.element, name):
153 raise AttributeError, name
154 return getattr(self.element, name)
158 def __init__(self, xml=None, namespaces=None):
160 self.namespaces = namespaces
161 self.default_namespace = None
163 if isinstance(xml, basestring):
165 if isinstance(xml, XmlElement):
167 self.namespaces = xml.namespaces
168 elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
169 self.parse_xml(etree.tostring(xml))
171 def parse_xml(self, xml):
173 parse rspec into etree
175 parser = etree.XMLParser(remove_blank_text=True)
177 tree = etree.parse(xml, parser)
179 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
181 tree = etree.parse(StringIO(xml), parser)
183 raise InvalidXML(str(e))
184 root = tree.getroot()
185 self.namespaces = dict(root.nsmap)
187 if 'default' not in self.namespaces and None in self.namespaces:
188 # If the 'None' exist, then it's pointing to the default namespace. This makes
189 # it hard for us to write xpath queries for the default naemspace because lxml
190 # wont understand a None prefix. We will just associate the default namespeace
191 # with a key named 'default'.
192 self.namespaces['default'] = self.namespaces.pop(None)
195 self.namespaces['default'] = 'default'
197 self.root = XmlElement(root, self.namespaces)
199 for key in self.root.attrib.keys():
200 if key.endswith('schemaLocation'):
201 # schema location should be at the end of the list
202 schema_parts = self.root.attrib[key].split(' ')
203 self.schema = schema_parts[1]
204 namespace, schema = schema_parts[0], schema_parts[1]
207 def parse_dict(self, d, root_tag_name='xml', element = None):
209 if self.root is None:
210 self.parse_xml('<%s/>' % root_tag_name)
217 # handle repeating fields
218 for (key, value) in d.items():
219 if isinstance(value, list):
222 if isinstance(val, dict):
223 child_element = etree.SubElement(element, key)
224 self.parse_dict(val, key, child_element)
225 elif isinstance(val, basestring):
226 child_element = etree.SubElement(element, key).text = val
228 elif isinstance(value, int):
229 d[key] = unicode(d[key])
233 # element.attrib.update will explode if DateTimes are in the
236 # looks like iteritems won't stand side-effects
238 if not isinstance(d[k],StringTypes):
241 element.attrib.update(d)
243 def validate(self, schema):
245 Validate against rng schema
247 relaxng_doc = etree.parse(schema)
248 relaxng = etree.RelaxNG(relaxng_doc)
249 if not relaxng(self.root):
250 error = relaxng.error_log.last_error
251 message = "%s (line %s)" % (error.message, error.line)
252 raise InvalidXML(message)
255 def xpath(self, xpath, namespaces=None):
257 namespaces = self.namespaces
258 return self.root.xpath(xpath, namespaces=namespaces)
260 def set(self, key, value):
261 return self.root.set(key, value)
263 def remove_attribute(self, name, element=None):
266 element.remove_attribute(name)
268 def add_element(self, *args, **kwds):
270 Wrapper around etree.SubElement(). Adds an element to
271 specified parent node. Adds element to root node is parent is
274 return self.root.add_element(*args, **kwds)
276 def remove_elements(self, name, element = None):
278 Removes all occurences of an element from the tree. Start at
279 specified root_node if specified, otherwise start at tree's root.
284 element.remove_elements(name)
286 def add_instance(self, *args, **kwds):
287 return self.root.add_instance(*args, **kwds)
289 def get_instance(self, *args, **kwds):
290 return self.root.get_instnace(*args, **kwds)
292 def get_element_attributes(self, elem=None, depth=0):
295 if not hasattr(elem, 'attrib'):
296 # this is probably not an element node with attribute. could be just and an
297 # attribute, return it
299 attrs = dict(elem.attrib)
300 attrs['text'] = str(elem.text).strip()
301 attrs['parent'] = elem.getparent()
302 if isinstance(depth, int) and depth > 0:
303 for child_elem in list(elem):
304 key = str(child_elem.tag)
306 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
308 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
310 attrs['child_nodes'] = list(elem)
313 def append(self, elem):
314 return self.root.append(elem)
316 def iterchildren(self):
317 return self.root.iterchildren()
319 def merge(self, in_xml):
326 return etree.tostring(self.root.element, encoding='UTF-8', pretty_print=True)
328 # XXX smbaker, for record.load_from_string
329 def todict(self, elem=None):
333 d.update(elem.attrib)
334 d['text'] = elem.text
335 for child in elem.iterchildren():
336 if child.tag not in d:
338 d[child.tag].append(self.todict(child))
340 if len(d)==1 and ("text" in d):
345 def save(self, filename):
346 f = open(filename, 'w')
347 f.write(self.toxml())
351 #if __name__ == '__main__':
352 # rspec = RSpec('/tmp/resources.rspec')