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 get(self, key, *args):
125 return self.element.get(key, *args)
127 def items(self): return self.element.items()
129 def set(self, key, value):
130 self.element.set(key, value)
132 def set_text(self, text):
133 self.element.text = text
135 def unset(self, key):
136 del self.element.attrib[key]
138 def iterchildren(self):
139 return self.element.iterchildren()
142 return etree.tostring(self.element, encoding='UTF-8', pretty_print=True)
149 def __init__(self, xml=None, namespaces=None):
151 self.namespaces = namespaces
152 self.default_namespace = None
154 if isinstance(xml, basestring):
156 if isinstance(xml, XmlElement):
158 self.namespaces = xml.namespaces
159 elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
160 self.parse_xml(etree.tostring(xml))
162 def parse_xml(self, xml):
164 parse rspec into etree
166 parser = etree.XMLParser(remove_blank_text=True)
168 tree = etree.parse(xml, parser)
170 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
172 tree = etree.parse(StringIO(xml), parser)
174 raise InvalidXML(str(e))
175 root = tree.getroot()
176 self.namespaces = dict(root.nsmap)
178 if 'default' not in self.namespaces and None in self.namespaces:
179 # If the 'None' exist, then it's pointing to the default namespace. This makes
180 # it hard for us to write xpath queries for the default naemspace because lxml
181 # wont understand a None prefix. We will just associate the default namespeace
182 # with a key named 'default'.
183 self.namespaces['default'] = self.namespaces.pop(None)
186 self.namespaces['default'] = 'default'
188 self.root = XmlElement(root, self.namespaces)
190 for key in self.root.attrib.keys():
191 if key.endswith('schemaLocation'):
192 # schema location should be at the end of the list
193 schema_parts = self.root.attrib[key].split(' ')
194 self.schema = schema_parts[1]
195 namespace, schema = schema_parts[0], schema_parts[1]
198 def parse_dict(self, d, root_tag_name='xml', element = None):
200 if self.root is None:
201 self.parse_xml('<%s/>' % root_tag_name)
208 # handle repeating fields
209 for (key, value) in d.items():
210 if isinstance(value, list):
213 if isinstance(val, dict):
214 child_element = etree.SubElement(element, key)
215 self.parse_dict(val, key, child_element)
216 elif isinstance(val, basestring):
217 child_element = etree.SubElement(element, key).text = val
219 elif isinstance(value, int):
220 d[key] = unicode(d[key])
224 # element.attrib.update will explode if DateTimes are in the
227 # looks like iteritems won't stand side-effects
229 if not isinstance(d[k],StringTypes):
232 element.attrib.update(d)
234 def validate(self, schema):
236 Validate against rng schema
238 relaxng_doc = etree.parse(schema)
239 relaxng = etree.RelaxNG(relaxng_doc)
240 if not relaxng(self.root):
241 error = relaxng.error_log.last_error
242 message = "%s (line %s)" % (error.message, error.line)
243 raise InvalidXML(message)
246 def xpath(self, xpath, namespaces=None):
248 namespaces = self.namespaces
249 return self.root.xpath(xpath, namespaces=namespaces)
251 def set(self, key, value, element=None):
254 return element.set(key, value)
256 def remove_attribute(self, name, element=None):
259 element.remove_attribute(name)
261 def add_element(self, *args, **kwds):
263 Wrapper around etree.SubElement(). Adds an element to
264 specified parent node. Adds element to root node is parent is
267 return self.root.add_element(*args, **kwds)
269 def remove_elements(self, name, element = None):
271 Removes all occurences of an element from the tree. Start at
272 specified root_node if specified, otherwise start at tree's root.
277 element.remove_elements(name)
279 def add_instance(self, *args, **kwds):
280 return self.root.add_instance(*args, **kwds)
282 def get_instance(self, *args, **kwds):
283 return self.root.get_instnace(*args, **kwds)
285 def get_element_attributes(self, elem=None, depth=0):
288 if not hasattr(elem, 'attrib'):
289 # this is probably not an element node with attribute. could be just and an
290 # attribute, return it
292 attrs = dict(elem.attrib)
293 attrs['text'] = str(elem.text).strip()
294 attrs['parent'] = elem.getparent()
295 if isinstance(depth, int) and depth > 0:
296 for child_elem in list(elem):
297 key = str(child_elem.tag)
299 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
301 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
303 attrs['child_nodes'] = list(elem)
306 def append(self, elem):
307 return self.root.append(elem)
309 def iterchildren(self):
310 return self.root.iterchildren()
312 def merge(self, in_xml):
319 return etree.tostring(self.root.element, encoding='UTF-8', pretty_print=True)
321 # XXX smbaker, for record.load_from_string
322 def todict(self, elem=None):
326 d.update(elem.attrib)
327 d['text'] = elem.text
328 for child in elem.iterchildren():
329 if child.tag not in d:
331 d[child.tag].append(self.todict(child))
333 if len(d)==1 and ("text" in d):
338 def save(self, filename):
339 f = open(filename, 'w')
340 f.write(self.toxml())
344 #if __name__ == '__main__':
345 # rspec = RSpec('/tmp/resources.rspec')