3 from sfa.util.faults import InvalidXML
4 from sfa.rspecs.elements.element import Element
6 from sfa.util.py23 import StringType
7 from sfa.util.py23 import StringIO
9 # helper functions to help build xpaths
15 def filter_value(key, value):
17 if isinstance(value, str):
19 value = value.replace('*', '')
20 xpath = 'contains(%s, "%s")' % (key, value)
22 xpath = '%s="%s"' % (key, value)
26 def xpath(filter=None):
32 for (key, value) in filter.items():
37 if isinstance(value, str):
38 filter_list.append(XpathFilter.filter_value(key, value))
39 elif isinstance(value, list):
41 [XpathFilter.filter_value(key, str(val)) for val in value])
42 filter_list.append(stmt)
44 xpath = ' and '.join(filter_list)
45 xpath = '[' + xpath + ']'
48 # a wrapper class around lxml.etree._Element
49 # the reason why we need this one is because of the limitations
50 # we've found in xpath to address documents with multiple namespaces defined
51 # in a nutshell, we deal with xml documents that have
52 # a default namespace defined (xmlns="http://default.com/") and specific prefixes defined
53 # (xmlns:foo="http://foo.com")
54 # according to the documentation instead of writing
55 # element.xpath ( "//node/foo:subnode" )
56 # we'd then need to write xpaths like
57 # element.xpath ( "//{http://default.com/}node/{http://foo.com}subnode" )
58 # which is a real pain..
59 # So just so we can keep some reasonable programming style we need to manage the
60 # namespace map that goes with the _Element (its internal .nsmap being
66 def __init__(self, element, namespaces):
67 self.element = element
68 self.namespaces = namespaces
70 # redefine as few methods as possible
71 def xpath(self, xpath, namespaces=None):
73 namespaces = self.namespaces
74 elems = self.element.xpath(xpath, namespaces=namespaces)
75 return [XmlElement(elem, namespaces) for elem in elems]
77 def add_element(self, tagname, **kwds):
78 element = etree.SubElement(self.element, tagname, **kwds)
79 return XmlElement(element, self.namespaces)
81 def append(self, elem):
82 if isinstance(elem, XmlElement):
83 self.element.append(elem.element)
85 self.element.append(elem)
88 return XmlElement(self.element.getparent(), self.namespaces)
90 def get_instance(self, instance_class=None, fields=None):
92 Returns an instance (dict) of this xml element. The instance
93 holds a reference to this xml element.
97 if not instance_class:
98 instance_class = Element
99 if not fields and hasattr(instance_class, 'fields'):
100 fields = instance_class.fields
103 instance = instance_class(self.attrib, self)
105 instance = instance_class({}, self)
107 if field in self.attrib:
108 instance[field] = self.attrib[field]
111 def add_instance(self, name, instance, fields=None):
113 Adds the specifed instance(s) as a child element of this xml
118 if not fields and hasattr(instance, 'keys'):
119 fields = instance.keys()
120 elem = self.add_element(name)
122 if field in instance and instance[field]:
123 elem.set(field, unicode(instance[field]))
126 def remove_elements(self, name):
128 Removes all occurences of an element from the tree. Start at
129 specified root_node if specified, otherwise start at tree's root.
132 if not element_name.startswith('//'):
133 element_name = '//' + element_name
134 elements = self.element.xpath('%s ' % name, namespaces=self.namespaces)
135 for element in elements:
136 parent = element.getparent()
137 parent.remove(element)
140 parent = self.getparent()
143 def remove(self, element):
144 if isinstance(element, XmlElement):
145 self.element.remove(element.element)
147 self.element.remove(element)
149 def set_text(self, text):
150 self.element.text = text
152 # Element does not have unset ?!?
153 def unset(self, key):
154 del self.element.attrib[key]
157 return etree.tostring(self.element, encoding='UTF-8', pretty_print=True)
162 # other method calls or attribute access like .text or .tag or .get
163 # are redirected on self.element
164 def __getattr__(self, name):
165 if not hasattr(self.element, name):
166 raise AttributeError(name)
167 return getattr(self.element, name)
172 def __init__(self, xml=None, namespaces=None):
174 self.namespaces = namespaces
175 self.default_namespace = None
177 if isinstance(xml, StringType):
179 if isinstance(xml, XmlElement):
181 self.namespaces = xml.namespaces
182 elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
183 self.parse_xml(etree.tostring(xml))
185 def parse_xml(self, xml):
187 parse rspec into etree
189 parser = etree.XMLParser(remove_blank_text=True)
191 tree = etree.parse(xml, parser)
193 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
195 tree = etree.parse(StringIO(xml), parser)
196 except Exception as e:
197 raise InvalidXML(str(e))
198 root = tree.getroot()
199 self.namespaces = dict(root.nsmap)
201 if 'default' not in self.namespaces and None in self.namespaces:
202 # If the 'None' exist, then it's pointing to the default namespace. This makes
203 # it hard for us to write xpath queries for the default naemspace because lxml
204 # wont understand a None prefix. We will just associate the default namespeace
205 # with a key named 'default'.
206 self.namespaces['default'] = self.namespaces.pop(None)
209 self.namespaces['default'] = 'default'
211 self.root = XmlElement(root, self.namespaces)
213 for key in self.root.attrib.keys():
214 if key.endswith('schemaLocation'):
215 # schemaLocation should be at the end of the list.
216 # Use list comprehension to filter out empty strings
218 x for x in self.root.attrib[key].split(' ') if x]
219 self.schema = schema_parts[1]
220 namespace, schema = schema_parts[0], schema_parts[1]
223 def parse_dict(self, d, root_tag_name='xml', element=None):
225 if self.root is None:
226 self.parse_xml('<%s/>' % root_tag_name)
227 element = self.root.element
233 # handle repeating fields
234 for (key, value) in d.items():
235 if isinstance(value, list):
238 if isinstance(val, dict):
239 child_element = etree.SubElement(element, key)
240 self.parse_dict(val, key, child_element)
241 elif isinstance(val, StringType):
242 child_element = etree.SubElement(
243 element, key).text = val
245 elif isinstance(value, int):
246 d[key] = unicode(d[key])
250 # element.attrib.update will explode if DateTimes are in the
253 # looks like iteritems won't stand side-effects
255 if not isinstance(d[k], StringType):
258 element.attrib.update(d)
260 def validate(self, schema):
262 Validate against rng schema
264 relaxng_doc = etree.parse(schema)
265 relaxng = etree.RelaxNG(relaxng_doc)
266 if not relaxng(self.root):
267 error = relaxng.error_log.last_error
268 message = "%s (line %s)" % (error.message, error.line)
269 raise InvalidXML(message)
272 def xpath(self, xpath, namespaces=None):
274 namespaces = self.namespaces
275 return self.root.xpath(xpath, namespaces=namespaces)
277 def set(self, key, value):
278 return self.root.set(key, value)
280 def remove_attribute(self, name, element=None):
283 element.remove_attribute(name)
285 def add_element(self, *args, **kwds):
287 Wrapper around etree.SubElement(). Adds an element to
288 specified parent node. Adds element to root node is parent is
291 return self.root.add_element(*args, **kwds)
293 def remove_elements(self, name, element=None):
295 Removes all occurences of an element from the tree. Start at
296 specified root_node if specified, otherwise start at tree's root.
301 element.remove_elements(name)
303 def add_instance(self, *args, **kwds):
304 return self.root.add_instance(*args, **kwds)
306 def get_instance(self, *args, **kwds):
307 return self.root.get_instnace(*args, **kwds)
309 def get_element_attributes(self, elem=None, depth=0):
312 if not hasattr(elem, 'attrib'):
313 # this is probably not an element node with attribute. could be just and an
314 # attribute, return it
316 attrs = dict(elem.attrib)
317 attrs['text'] = str(elem.text).strip()
318 attrs['parent'] = elem.getparent()
319 if isinstance(depth, int) and depth > 0:
320 for child_elem in list(elem):
321 key = str(child_elem.tag)
323 attrs[key] = [self.get_element_attributes(
324 child_elem, depth - 1)]
327 self.get_element_attributes(child_elem, depth - 1))
329 attrs['child_nodes'] = list(elem)
332 def append(self, elem):
333 return self.root.append(elem)
335 def iterchildren(self):
336 return self.root.iterchildren()
338 def merge(self, in_xml):
345 return etree.tostring(self.root.element, encoding='UTF-8', pretty_print=True)
347 # XXX smbaker, for record.load_from_string
348 def todict(self, elem=None):
352 d.update(elem.attrib)
353 d['text'] = elem.text
354 for child in elem.iterchildren():
355 if child.tag not in d:
357 d[child.tag].append(self.todict(child))
359 if len(d) == 1 and ("text" in d):
364 def save(self, filename):
365 f = open(filename, 'w')
366 f.write(self.toxml())
370 # if __name__ == '__main__':
371 # rspec = RSpec('/tmp/resources.rspec')