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):
44 self.namespaces = namespaces
45 self.attrib = node.attrib
48 def xpath(self, xpath, namespaces=None):
50 namespaces = self.namespaces
51 elems = self.node.xpath(xpath, namespaces=namespaces)
52 return [XmlNode(elem, namespaces) for elem in elems]
54 def add_element(self, tagname, **kwds):
55 element = etree.SubElement(self.node, tagname, **kwds)
56 return XmlNode(element, self.namespaces)
58 def append(self, elem):
59 if isinstance(elem, XmlNode):
60 self.node.append(elem.node)
62 self.node.append(elem)
65 return XmlNode(self.node.getparent(), self.namespaces)
67 def remove_elements(name):
69 Removes all occurences of an element from the tree. Start at
70 specified root_node if specified, otherwise start at tree's root.
73 if not element_name.startswith('//'):
74 element_name = '//' + element_name
75 elements = self.node.xpath('%s ' % name, namespaces=self.namespaces)
76 for element in elements:
77 parent = element.getparent()
78 parent.remove(element)
81 self.node.remove(element)
83 def get(self, key, *args):
84 return self.node.get(key, *args)
86 def items(self): return self.node.items()
88 def set(self, key, value):
89 self.node.set(key, value)
91 def set_text(self, text):
95 del self.node.attrib[key]
97 def iterchildren(self):
98 return self.node.iterchildren()
101 return etree.tostring(self.node, encoding='UTF-8', pretty_print=True)
108 def __init__(self, xml=None, namespaces=None):
110 self.namespaces = namespaces
111 self.default_namespace = None
113 if isinstance(xml, basestring):
115 if isinstance(xml, XmlNode):
117 self.namespaces = xml.namespaces
118 elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
119 self.parse_xml(etree.tostring(xml))
121 def parse_xml(self, xml):
123 parse rspec into etree
125 parser = etree.XMLParser(remove_blank_text=True)
127 tree = etree.parse(xml, parser)
129 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
131 tree = etree.parse(StringIO(xml), parser)
133 raise InvalidXML(str(e))
134 root = tree.getroot()
135 self.namespaces = dict(root.nsmap)
137 if 'default' not in self.namespaces and None in self.namespaces:
138 # If the 'None' exist, then it's pointing to the default namespace. This makes
139 # it hard for us to write xpath queries for the default naemspace because lxml
140 # wont understand a None prefix. We will just associate the default namespeace
141 # with a key named 'default'.
142 self.namespaces['default'] = self.namespaces.pop(None)
145 self.namespaces['default'] = 'default'
147 self.root = XmlNode(root, self.namespaces)
149 for key in self.root.attrib.keys():
150 if key.endswith('schemaLocation'):
151 # schema location should be at the end of the list
152 schema_parts = self.root.attrib[key].split(' ')
153 self.schema = schema_parts[1]
154 namespace, schema = schema_parts[0], schema_parts[1]
157 def parse_dict(self, d, root_tag_name='xml', element = None):
159 if self.root is None:
160 self.parse_xml('<%s/>' % root_tag_name)
167 # handle repeating fields
168 for (key, value) in d.items():
169 if isinstance(value, list):
172 if isinstance(val, dict):
173 child_element = etree.SubElement(element, key)
174 self.parse_dict(val, key, child_element)
175 elif isinstance(val, basestring):
176 child_element = etree.SubElement(element, key).text = val
178 elif isinstance(value, int):
179 d[key] = unicode(d[key])
183 # element.attrib.update will explode if DateTimes are in the
186 # looks like iteritems won't stand side-effects
188 if not isinstance(d[k],StringTypes):
191 element.attrib.update(d)
193 def validate(self, schema):
195 Validate against rng schema
197 relaxng_doc = etree.parse(schema)
198 relaxng = etree.RelaxNG(relaxng_doc)
199 if not relaxng(self.root):
200 error = relaxng.error_log.last_error
201 message = "%s (line %s)" % (error.message, error.line)
202 raise InvalidXML(message)
205 def xpath(self, xpath, namespaces=None):
207 namespaces = self.namespaces
208 return self.root.xpath(xpath, namespaces=namespaces)
210 def set(self, key, value, node=None):
213 return node.set(key, value)
215 def remove_attribute(self, name, node=None):
218 node.remove_attribute(name)
221 def add_element(self, name, **kwds):
223 Wrapper around etree.SubElement(). Adds an element to
224 specified parent node. Adds element to root node is parent is
228 xmlnode = parent.add_element(name, *kwds)
231 def remove_elements(self, name, node = None):
233 Removes all occurences of an element from the tree. Start at
234 specified root_node if specified, otherwise start at tree's root.
239 node.remove_elements(name)
241 def attributes_list(self, elem):
242 # convert a list of attribute tags into list of tuples
243 # (tagnme, text_value)
247 opts.append((e.tag, str(e.text).strip()))
250 def get_element_attributes(self, elem=None, depth=0):
252 elem = self.root_node
253 if not hasattr(elem, 'attrib'):
254 # this is probably not an element node with attribute. could be just and an
255 # attribute, return it
257 attrs = dict(elem.attrib)
258 attrs['text'] = str(elem.text).strip()
259 attrs['parent'] = elem.getparent()
260 if isinstance(depth, int) and depth > 0:
261 for child_elem in list(elem):
262 key = str(child_elem.tag)
264 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
266 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
268 attrs['child_nodes'] = list(elem)
271 def merge(self, in_xml):
278 return etree.tostring(self.root.node, encoding='UTF-8', pretty_print=True)
280 # XXX smbaker, for record.load_from_string
281 def todict(self, elem=None):
285 d.update(elem.attrib)
286 d['text'] = elem.text
287 for child in elem.iterchildren():
288 if child.tag not in d:
290 d[child.tag].append(self.todict(child))
292 if len(d)==1 and ("text" in d):
297 def save(self, filename):
298 f = open(filename, 'w')
299 f.write(self.toxml())
303 #if __name__ == '__main__':
304 # rspec = RSpec('/tmp/resources.rspec')