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 # schemaLocation should be at the end of the list.
202 # Use list comprehension to filter out empty strings
203 schema_parts = [x for x in self.root.attrib[key].split(' ') if x]
204 self.schema = schema_parts[1]
205 namespace, schema = schema_parts[0], schema_parts[1]
208 def parse_dict(self, d, root_tag_name='xml', element = None):
210 if self.root is None:
211 self.parse_xml('<%s/>' % root_tag_name)
212 element = self.root.element
218 # handle repeating fields
219 for (key, value) in d.items():
220 if isinstance(value, list):
223 if isinstance(val, dict):
224 child_element = etree.SubElement(element, key)
225 self.parse_dict(val, key, child_element)
226 elif isinstance(val, basestring):
227 child_element = etree.SubElement(element, key).text = val
229 elif isinstance(value, int):
230 d[key] = unicode(d[key])
234 # element.attrib.update will explode if DateTimes are in the
237 # looks like iteritems won't stand side-effects
239 if not isinstance(d[k],StringTypes):
242 element.attrib.update(d)
244 def validate(self, schema):
246 Validate against rng schema
248 relaxng_doc = etree.parse(schema)
249 relaxng = etree.RelaxNG(relaxng_doc)
250 if not relaxng(self.root):
251 error = relaxng.error_log.last_error
252 message = "%s (line %s)" % (error.message, error.line)
253 raise InvalidXML(message)
256 def xpath(self, xpath, namespaces=None):
258 namespaces = self.namespaces
259 return self.root.xpath(xpath, namespaces=namespaces)
261 def set(self, key, value):
262 return self.root.set(key, value)
264 def remove_attribute(self, name, element=None):
267 element.remove_attribute(name)
269 def add_element(self, *args, **kwds):
271 Wrapper around etree.SubElement(). Adds an element to
272 specified parent node. Adds element to root node is parent is
275 return self.root.add_element(*args, **kwds)
277 def remove_elements(self, name, element = None):
279 Removes all occurences of an element from the tree. Start at
280 specified root_node if specified, otherwise start at tree's root.
285 element.remove_elements(name)
287 def add_instance(self, *args, **kwds):
288 return self.root.add_instance(*args, **kwds)
290 def get_instance(self, *args, **kwds):
291 return self.root.get_instnace(*args, **kwds)
293 def get_element_attributes(self, elem=None, depth=0):
296 if not hasattr(elem, 'attrib'):
297 # this is probably not an element node with attribute. could be just and an
298 # attribute, return it
300 attrs = dict(elem.attrib)
301 attrs['text'] = str(elem.text).strip()
302 attrs['parent'] = elem.getparent()
303 if isinstance(depth, int) and depth > 0:
304 for child_elem in list(elem):
305 key = str(child_elem.tag)
307 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
309 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
311 attrs['child_nodes'] = list(elem)
314 def append(self, elem):
315 return self.root.append(elem)
317 def iterchildren(self):
318 return self.root.iterchildren()
320 def merge(self, in_xml):
327 return etree.tostring(self.root.element, encoding='UTF-8', pretty_print=True)
329 # XXX smbaker, for record.load_from_string
330 def todict(self, elem=None):
334 d.update(elem.attrib)
335 d['text'] = elem.text
336 for child in elem.iterchildren():
337 if child.tag not in d:
339 d[child.tag].append(self.todict(child))
341 if len(d)==1 and ("text" in d):
346 def save(self, filename):
347 f = open(filename, 'w')
348 f.write(self.toxml())
352 #if __name__ == '__main__':
353 # rspec = RSpec('/tmp/resources.rspec')