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.text = element.text
45 self.namespaces = namespaces
46 self.attrib = element.attrib
49 def xpath(self, xpath, namespaces=None):
51 namespaces = self.namespaces
52 elems = self.element.xpath(xpath, namespaces=namespaces)
53 return [XmlElement(elem, namespaces) for elem in elems]
55 def add_element(self, tagname, **kwds):
56 element = etree.SubElement(self.element, tagname, **kwds)
57 return XmlElement(element, self.namespaces)
59 def append(self, elem):
60 if isinstance(elem, XmlElement):
61 self.element.append(elem.element)
63 self.element.append(elem)
66 return XmlElement(self.element.getparent(), self.namespaces)
68 def get_instance(self, instance_class=None, fields=[]):
70 Returns an instance (dict) of this xml element. The instance
71 holds a reference this xml element.
73 if not instance_class:
74 instance_class = Element
75 if not fields and hasattr(instance_class, 'fields'):
76 fields = instance_class.fields
79 instance = instance_class(self.attrib, self)
81 instance = instance_class({}, self)
83 if field in self.attrib:
84 instance[field] = self.attrib[field]
87 def add_instance(self, name, instance, fields=[]):
89 Adds the specifed instance(s) as a child element of this xml
92 if not fields and hasattr(instance, 'keys'):
93 fields = instance.keys()
94 elem = self.add_element(name)
96 if field in instance and instance[field]:
97 elem.set(field, unicode(instance[field]))
100 def remove_elements(self, name):
102 Removes all occurences of an element from the tree. Start at
103 specified root_node if specified, otherwise start at tree's root.
106 if not element_name.startswith('//'):
107 element_name = '//' + element_name
108 elements = self.element.xpath('%s ' % name, namespaces=self.namespaces)
109 for element in elements:
110 parent = element.getparent()
111 parent.remove(element)
113 def remove(self, element):
114 if isinstance(element, XmlElement):
115 self.element.remove(element.element)
117 self.element.remove(element)
119 def get(self, key, *args):
120 return self.element.get(key, *args)
122 def items(self): return self.element.items()
124 def set(self, key, value):
125 self.element.set(key, value)
127 def set_text(self, text):
128 self.element.text = text
130 def unset(self, key):
131 del self.element.attrib[key]
133 def iterchildren(self):
134 return self.element.iterchildren()
137 return etree.tostring(self.element, encoding='UTF-8', pretty_print=True)
144 def __init__(self, xml=None, namespaces=None):
146 self.namespaces = namespaces
147 self.default_namespace = None
149 if isinstance(xml, basestring):
151 if isinstance(xml, XmlElement):
153 self.namespaces = xml.namespaces
154 elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
155 self.parse_xml(etree.tostring(xml))
157 def parse_xml(self, xml):
159 parse rspec into etree
161 parser = etree.XMLParser(remove_blank_text=True)
163 tree = etree.parse(xml, parser)
165 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
167 tree = etree.parse(StringIO(xml), parser)
169 raise InvalidXML(str(e))
170 root = tree.getroot()
171 self.namespaces = dict(root.nsmap)
173 if 'default' not in self.namespaces and None in self.namespaces:
174 # If the 'None' exist, then it's pointing to the default namespace. This makes
175 # it hard for us to write xpath queries for the default naemspace because lxml
176 # wont understand a None prefix. We will just associate the default namespeace
177 # with a key named 'default'.
178 self.namespaces['default'] = self.namespaces.pop(None)
181 self.namespaces['default'] = 'default'
183 self.root = XmlElement(root, self.namespaces)
185 for key in self.root.attrib.keys():
186 if key.endswith('schemaLocation'):
187 # schema location should be at the end of the list
188 schema_parts = self.root.attrib[key].split(' ')
189 self.schema = schema_parts[1]
190 namespace, schema = schema_parts[0], schema_parts[1]
193 def parse_dict(self, d, root_tag_name='xml', element = None):
195 if self.root is None:
196 self.parse_xml('<%s/>' % root_tag_name)
203 # handle repeating fields
204 for (key, value) in d.items():
205 if isinstance(value, list):
208 if isinstance(val, dict):
209 child_element = etree.SubElement(element, key)
210 self.parse_dict(val, key, child_element)
211 elif isinstance(val, basestring):
212 child_element = etree.SubElement(element, key).text = val
214 elif isinstance(value, int):
215 d[key] = unicode(d[key])
219 # element.attrib.update will explode if DateTimes are in the
222 # looks like iteritems won't stand side-effects
224 if not isinstance(d[k],StringTypes):
227 element.attrib.update(d)
229 def validate(self, schema):
231 Validate against rng schema
233 relaxng_doc = etree.parse(schema)
234 relaxng = etree.RelaxNG(relaxng_doc)
235 if not relaxng(self.root):
236 error = relaxng.error_log.last_error
237 message = "%s (line %s)" % (error.message, error.line)
238 raise InvalidXML(message)
241 def xpath(self, xpath, namespaces=None):
243 namespaces = self.namespaces
244 return self.root.xpath(xpath, namespaces=namespaces)
246 def set(self, key, value, element=None):
249 return element.set(key, value)
251 def remove_attribute(self, name, element=None):
254 element.remove_attribute(name)
256 def add_element(self, *args, **kwds):
258 Wrapper around etree.SubElement(). Adds an element to
259 specified parent node. Adds element to root node is parent is
262 return self.root.add_element(*args, **kwds)
264 def remove_elements(self, name, element = None):
266 Removes all occurences of an element from the tree. Start at
267 specified root_node if specified, otherwise start at tree's root.
272 element.remove_elements(name)
274 def add_instance(self, *args, **kwds):
275 return self.root.add_instance(*args, **kwds)
277 def get_instance(self, *args, **kwds):
278 return self.root.get_instnace(*args, **kwds)
280 def get_element_attributes(self, elem=None, depth=0):
283 if not hasattr(elem, 'attrib'):
284 # this is probably not an element node with attribute. could be just and an
285 # attribute, return it
287 attrs = dict(elem.attrib)
288 attrs['text'] = str(elem.text).strip()
289 attrs['parent'] = elem.getparent()
290 if isinstance(depth, int) and depth > 0:
291 for child_elem in list(elem):
292 key = str(child_elem.tag)
294 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
296 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
298 attrs['child_nodes'] = list(elem)
301 def append(self, elem):
302 return self.root.append(elem)
304 def iterchildren(self):
305 return self.root.iterchildren()
307 def merge(self, in_xml):
314 return etree.tostring(self.root.element, encoding='UTF-8', pretty_print=True)
316 # XXX smbaker, for record.load_from_string
317 def todict(self, elem=None):
321 d.update(elem.attrib)
322 d['text'] = elem.text
323 for child in elem.iterchildren():
324 if child.tag not in d:
326 d[child.tag].append(self.todict(child))
328 if len(d)==1 and ("text" in d):
333 def save(self, filename):
334 f = open(filename, 'w')
335 f.write(self.toxml())
339 #if __name__ == '__main__':
340 # rspec = RSpec('/tmp/resources.rspec')