2 from types import StringTypes
4 from StringIO import StringIO
5 from sfa.util.faults import InvalidXML
10 def filter_value(key, value):
12 if isinstance(value, str):
14 value = value.replace('*', '')
15 xpath = 'contains(%s, "%s")' % (key, value)
17 xpath = '%s="%s"' % (key, value)
25 for (key, value) in filter.items():
30 if isinstance(value, str):
31 filter_list.append(XpathFilter.filter_value(key, value))
32 elif isinstance(value, list):
33 stmt = ' or '.join([XpathFilter.filter_value(key, str(val)) for val in value])
34 filter_list.append(stmt)
36 xpath = ' and '.join(filter_list)
37 xpath = '[' + xpath + ']'
41 def __init__(self, node, namespaces):
43 self.namespaces = namespaces
44 self.attrib = node.attrib
46 def xpath(self, xpath, namespaces=None):
48 namespaces = self.namespaces
49 return self.node.xpath(xpath, namespaces=namespaces)
51 def add_element(name, *args, **kwds):
52 element = etree.SubElement(name, args, kwds)
53 return XmlNode(element, self.namespaces)
55 def remove_elements(name):
57 Removes all occurences of an element from the tree. Start at
58 specified root_node if specified, otherwise start at tree's root.
61 if not element_name.startswith('//'):
62 element_name = '//' + element_name
63 elements = self.node.xpath('%s ' % name, namespaces=self.namespaces)
64 for element in elements:
65 parent = element.getparent()
66 parent.remove(element)
68 def set(self, key, value):
69 self.node.set(key, value)
71 def set_text(self, text):
75 del self.node.attrib[key]
78 return etree.tostring(self.node, encoding='UTF-8', pretty_print=True)
85 def __init__(self, xml=None, namespaces=None):
87 self.namespaces = namespaces
88 self.default_namespace = None
90 if isinstance(xml, basestring):
92 if isinstance(xml, XmlNode):
94 self.namespces = xml.namespaces
95 elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
96 self.parse_xml(etree.tostring(xml))
98 def parse_xml(self, xml):
100 parse rspec into etree
102 parser = etree.XMLParser(remove_blank_text=True)
104 tree = etree.parse(xml, parser)
106 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
108 tree = etree.parse(StringIO(xml), parser)
110 raise InvalidXML(str(e))
111 root = tree.getroot()
112 self.namespaces = dict(root.nsmap)
114 if 'default' not in self.namespaces and None in self.namespaces:
115 # If the 'None' exist, then it's pointing to the default namespace. This makes
116 # it hard for us to write xpath queries for the default naemspace because lxml
117 # wont understand a None prefix. We will just associate the default namespeace
118 # with a key named 'default'.
119 self.namespaces['default'] = self.namespaces.pop(None)
122 self.namespaces['default'] = 'default'
124 self.root = XmlNode(root, self.namespaces)
126 for key in self.root.attrib.keys():
127 if key.endswith('schemaLocation'):
128 # schema location should be at the end of the list
129 schema_parts = self.root.attrib[key].split(' ')
130 self.schema = schema_parts[1]
131 namespace, schema = schema_parts[0], schema_parts[1]
134 def parse_dict(self, d, root_tag_name='xml', element = None):
136 if self.root is None:
137 self.parse_xml('<%s/>' % root_tag_name)
144 # handle repeating fields
145 for (key, value) in d.items():
146 if isinstance(value, list):
149 if isinstance(val, dict):
150 child_element = etree.SubElement(element, key)
151 self.parse_dict(val, key, child_element)
152 elif isinstance(val, basestring):
153 child_element = etree.SubElement(element, key).text = val
155 elif isinstance(value, int):
156 d[key] = unicode(d[key])
160 # element.attrib.update will explode if DateTimes are in the
163 # looks like iteritems won't stand side-effects
165 if not isinstance(d[k],StringTypes):
168 element.attrib.update(d)
170 def validate(self, schema):
172 Validate against rng schema
174 relaxng_doc = etree.parse(schema)
175 relaxng = etree.RelaxNG(relaxng_doc)
176 if not relaxng(self.root):
177 error = relaxng.error_log.last_error
178 message = "%s (line %s)" % (error.message, error.line)
179 raise InvalidXML(message)
182 def xpath(self, xpath, namespaces=None):
184 namespaces = self.namespaces
185 return self.root.xpath(xpath, namespaces=namespaces)
187 def set(self, key, value, node=None):
190 return node.set(key, value)
192 def remove_attribute(self, name, node=None):
195 node.remove_attribute(name)
198 def add_element(self, name, attrs={}, parent=None, text=""):
200 Wrapper around etree.SubElement(). Adds an element to
201 specified parent node. Adds element to root node is parent is
206 element = etree.SubElement(parent, name)
209 if isinstance(attrs, dict):
211 element.set(attr, attrs[attr])
212 return XmlNode(element, self.namespaces)
214 def remove_elements(self, name, node = None):
216 Removes all occurences of an element from the tree. Start at
217 specified root_node if specified, otherwise start at tree's root.
222 node.remove_elements(name)
224 def attributes_list(self, elem):
225 # convert a list of attribute tags into list of tuples
226 # (tagnme, text_value)
230 opts.append((e.tag, str(e.text).strip()))
233 def get_element_attributes(self, elem=None, depth=0):
235 elem = self.root_node
236 if not hasattr(elem, 'attrib'):
237 # this is probably not an element node with attribute. could be just and an
238 # attribute, return it
240 attrs = dict(elem.attrib)
241 attrs['text'] = str(elem.text).strip()
242 attrs['parent'] = elem.getparent()
243 if isinstance(depth, int) and depth > 0:
244 for child_elem in list(elem):
245 key = str(child_elem.tag)
247 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
249 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
251 attrs['child_nodes'] = list(elem)
254 def merge(self, in_xml):
261 return etree.tostring(self.root, encoding='UTF-8', pretty_print=True)
263 # XXX smbaker, for record.load_from_string
264 def todict(self, elem=None):
268 d.update(elem.attrib)
269 d['text'] = elem.text
270 for child in elem.iterchildren():
271 if child.tag not in d:
273 d[child.tag].append(self.todict(child))
275 if len(d)==1 and ("text" in d):
280 def save(self, filename):
281 f = open(filename, 'w')
282 f.write(self.toxml())
286 #if __name__ == '__main__':
287 # rspec = RSpec('/tmp/resources.rspec')