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
11 def filter_value(key, value):
13 if isinstance(value, str):
15 value = value.replace('*', '')
16 xpath = 'contains(%s, "%s")' % (key, value)
18 xpath = '%s="%s"' % (key, value)
26 for (key, value) in filter.items():
31 if isinstance(value, str):
32 filter_list.append(XpathFilter.filter_value(key, value))
33 elif isinstance(value, list):
34 stmt = ' or '.join([XpathFilter.filter_value(key, str(val)) for val in value])
35 filter_list.append(stmt)
37 xpath = ' and '.join(filter_list)
38 xpath = '[' + xpath + ']'
42 def __init__(self, element, namespaces):
43 self.element = element
44 self.tag = element.tag
45 self.text = element.text
46 self.attrib = element.attrib
47 self.namespaces = namespaces
50 def xpath(self, xpath, namespaces=None):
52 namespaces = self.namespaces
53 elems = self.element.xpath(xpath, namespaces=namespaces)
54 return [XmlElement(elem, namespaces) for elem in elems]
56 def add_element(self, tagname, **kwds):
57 element = etree.SubElement(self.element, tagname, **kwds)
58 return XmlElement(element, self.namespaces)
60 def append(self, elem):
61 if isinstance(elem, XmlElement):
62 self.element.append(elem.element)
64 self.element.append(elem)
67 return XmlElement(self.element.getparent(), self.namespaces)
69 def get_instance(self, instance_class=None, fields=[]):
71 Returns an instance (dict) of this xml element. The instance
72 holds a reference this xml element.
74 if not instance_class:
75 instance_class = Element
76 if not fields and hasattr(instance_class, 'fields'):
77 fields = instance_class.fields
80 instance = instance_class(self.attrib, self)
82 instance = instance_class({}, self)
84 if field in self.attrib:
85 instance[field] = self.attrib[field]
88 def add_instance(self, name, instance, fields=[]):
90 Adds the specifed instance(s) as a child element of this xml
93 if not fields and hasattr(instance, 'keys'):
94 fields = instance.keys()
95 elem = self.add_element(name)
97 if field in instance and instance[field]:
98 elem.set(field, unicode(instance[field]))
101 def remove_elements(self, name):
103 Removes all occurences of an element from the tree. Start at
104 specified root_node if specified, otherwise start at tree's root.
107 if not element_name.startswith('//'):
108 element_name = '//' + element_name
109 elements = self.element.xpath('%s ' % name, namespaces=self.namespaces)
110 for element in elements:
111 parent = element.getparent()
112 parent.remove(element)
115 parent = self.getparent()
118 def remove(self, element):
119 if isinstance(element, XmlElement):
120 self.element.remove(element.element)
122 self.element.remove(element)
124 def set_text(self, text):
125 self.element.text = text
127 # Element does not have unset ?!?
128 def unset(self, key):
129 del self.element.attrib[key]
132 return etree.tostring(self.element, encoding='UTF-8', pretty_print=True)
137 ### other method calls or attribute access like .text or .tag or .get
138 # are redirected on self.element
139 def __getattr__ (self, name):
140 if not hasattr(self.element, name):
141 raise AttributeError, name
142 return getattr(self.element, name)
146 def __init__(self, xml=None, namespaces=None):
148 self.namespaces = namespaces
149 self.default_namespace = None
151 if isinstance(xml, basestring):
153 if isinstance(xml, XmlElement):
155 self.namespaces = xml.namespaces
156 elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
157 self.parse_xml(etree.tostring(xml))
159 def parse_xml(self, xml):
161 parse rspec into etree
163 parser = etree.XMLParser(remove_blank_text=True)
165 tree = etree.parse(xml, parser)
167 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
169 tree = etree.parse(StringIO(xml), parser)
171 raise InvalidXML(str(e))
172 root = tree.getroot()
173 self.namespaces = dict(root.nsmap)
175 if 'default' not in self.namespaces and None in self.namespaces:
176 # If the 'None' exist, then it's pointing to the default namespace. This makes
177 # it hard for us to write xpath queries for the default naemspace because lxml
178 # wont understand a None prefix. We will just associate the default namespeace
179 # with a key named 'default'.
180 self.namespaces['default'] = self.namespaces.pop(None)
183 self.namespaces['default'] = 'default'
185 self.root = XmlElement(root, self.namespaces)
187 for key in self.root.attrib.keys():
188 if key.endswith('schemaLocation'):
189 # schema location should be at the end of the list
190 schema_parts = self.root.attrib[key].split(' ')
191 self.schema = schema_parts[1]
192 namespace, schema = schema_parts[0], schema_parts[1]
195 def parse_dict(self, d, root_tag_name='xml', element = None):
197 if self.root is None:
198 self.parse_xml('<%s/>' % root_tag_name)
205 # handle repeating fields
206 for (key, value) in d.items():
207 if isinstance(value, list):
210 if isinstance(val, dict):
211 child_element = etree.SubElement(element, key)
212 self.parse_dict(val, key, child_element)
213 elif isinstance(val, basestring):
214 child_element = etree.SubElement(element, key).text = val
216 elif isinstance(value, int):
217 d[key] = unicode(d[key])
221 # element.attrib.update will explode if DateTimes are in the
224 # looks like iteritems won't stand side-effects
226 if not isinstance(d[k],StringTypes):
229 element.attrib.update(d)
231 def validate(self, schema):
233 Validate against rng schema
235 relaxng_doc = etree.parse(schema)
236 relaxng = etree.RelaxNG(relaxng_doc)
237 if not relaxng(self.root):
238 error = relaxng.error_log.last_error
239 message = "%s (line %s)" % (error.message, error.line)
240 raise InvalidXML(message)
243 def xpath(self, xpath, namespaces=None):
245 namespaces = self.namespaces
246 return self.root.xpath(xpath, namespaces=namespaces)
248 def set(self, key, value, element=None):
251 return element.set(key, value)
253 def remove_attribute(self, name, element=None):
256 element.remove_attribute(name)
258 def add_element(self, *args, **kwds):
260 Wrapper around etree.SubElement(). Adds an element to
261 specified parent node. Adds element to root node is parent is
264 return self.root.add_element(*args, **kwds)
266 def remove_elements(self, name, element = None):
268 Removes all occurences of an element from the tree. Start at
269 specified root_node if specified, otherwise start at tree's root.
274 element.remove_elements(name)
276 def add_instance(self, *args, **kwds):
277 return self.root.add_instance(*args, **kwds)
279 def get_instance(self, *args, **kwds):
280 return self.root.get_instnace(*args, **kwds)
282 def get_element_attributes(self, elem=None, depth=0):
285 if not hasattr(elem, 'attrib'):
286 # this is probably not an element node with attribute. could be just and an
287 # attribute, return it
289 attrs = dict(elem.attrib)
290 attrs['text'] = str(elem.text).strip()
291 attrs['parent'] = elem.getparent()
292 if isinstance(depth, int) and depth > 0:
293 for child_elem in list(elem):
294 key = str(child_elem.tag)
296 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
298 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
300 attrs['child_nodes'] = list(elem)
303 def append(self, elem):
304 return self.root.append(elem)
306 def iterchildren(self):
307 return self.root.iterchildren()
309 def merge(self, in_xml):
316 return etree.tostring(self.root.element, encoding='UTF-8', pretty_print=True)
318 # XXX smbaker, for record.load_from_string
319 def todict(self, elem=None):
323 d.update(elem.attrib)
324 d['text'] = elem.text
325 for child in elem.iterchildren():
326 if child.tag not in d:
328 d[child.tag].append(self.todict(child))
330 if len(d)==1 and ("text" in d):
335 def save(self, filename):
336 f = open(filename, 'w')
337 f.write(self.toxml())
341 #if __name__ == '__main__':
342 # rspec = RSpec('/tmp/resources.rspec')