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)
64 def remove_elements(name):
66 Removes all occurences of an element from the tree. Start at
67 specified root_node if specified, otherwise start at tree's root.
70 if not element_name.startswith('//'):
71 element_name = '//' + element_name
72 elements = self.node.xpath('%s ' % name, namespaces=self.namespaces)
73 for element in elements:
74 parent = element.getparent()
75 parent.remove(element)
78 self.node.remove(element)
80 def set(self, key, value):
81 self.node.set(key, value)
83 def set_text(self, text):
87 del self.node.attrib[key]
89 def iterchildren(self):
90 return self.node.iterchildren()
93 return etree.tostring(self.node, encoding='UTF-8', pretty_print=True)
100 def __init__(self, xml=None, namespaces=None):
102 self.namespaces = namespaces
103 self.default_namespace = None
105 if isinstance(xml, basestring):
107 if isinstance(xml, XmlNode):
109 self.namespaces = xml.namespaces
110 elif isinstance(xml, etree._ElementTree) or isinstance(xml, etree._Element):
111 self.parse_xml(etree.tostring(xml))
113 def parse_xml(self, xml):
115 parse rspec into etree
117 parser = etree.XMLParser(remove_blank_text=True)
119 tree = etree.parse(xml, parser)
121 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
123 tree = etree.parse(StringIO(xml), parser)
125 raise InvalidXML(str(e))
126 root = tree.getroot()
127 self.namespaces = dict(root.nsmap)
129 if 'default' not in self.namespaces and None in self.namespaces:
130 # If the 'None' exist, then it's pointing to the default namespace. This makes
131 # it hard for us to write xpath queries for the default naemspace because lxml
132 # wont understand a None prefix. We will just associate the default namespeace
133 # with a key named 'default'.
134 self.namespaces['default'] = self.namespaces.pop(None)
137 self.namespaces['default'] = 'default'
139 self.root = XmlNode(root, self.namespaces)
141 for key in self.root.attrib.keys():
142 if key.endswith('schemaLocation'):
143 # schema location should be at the end of the list
144 schema_parts = self.root.attrib[key].split(' ')
145 self.schema = schema_parts[1]
146 namespace, schema = schema_parts[0], schema_parts[1]
149 def parse_dict(self, d, root_tag_name='xml', element = None):
151 if self.root is None:
152 self.parse_xml('<%s/>' % root_tag_name)
159 # handle repeating fields
160 for (key, value) in d.items():
161 if isinstance(value, list):
164 if isinstance(val, dict):
165 child_element = etree.SubElement(element, key)
166 self.parse_dict(val, key, child_element)
167 elif isinstance(val, basestring):
168 child_element = etree.SubElement(element, key).text = val
170 elif isinstance(value, int):
171 d[key] = unicode(d[key])
175 # element.attrib.update will explode if DateTimes are in the
178 # looks like iteritems won't stand side-effects
180 if not isinstance(d[k],StringTypes):
183 element.attrib.update(d)
185 def validate(self, schema):
187 Validate against rng schema
189 relaxng_doc = etree.parse(schema)
190 relaxng = etree.RelaxNG(relaxng_doc)
191 if not relaxng(self.root):
192 error = relaxng.error_log.last_error
193 message = "%s (line %s)" % (error.message, error.line)
194 raise InvalidXML(message)
197 def xpath(self, xpath, namespaces=None):
199 namespaces = self.namespaces
200 return self.root.xpath(xpath, namespaces=namespaces)
202 def set(self, key, value, node=None):
205 return node.set(key, value)
207 def remove_attribute(self, name, node=None):
210 node.remove_attribute(name)
213 def add_element(self, name, **kwds):
215 Wrapper around etree.SubElement(). Adds an element to
216 specified parent node. Adds element to root node is parent is
220 xmlnode = parent.add_element(name, *kwds)
223 def remove_elements(self, name, node = None):
225 Removes all occurences of an element from the tree. Start at
226 specified root_node if specified, otherwise start at tree's root.
231 node.remove_elements(name)
233 def attributes_list(self, elem):
234 # convert a list of attribute tags into list of tuples
235 # (tagnme, text_value)
239 opts.append((e.tag, str(e.text).strip()))
242 def get_element_attributes(self, elem=None, depth=0):
244 elem = self.root_node
245 if not hasattr(elem, 'attrib'):
246 # this is probably not an element node with attribute. could be just and an
247 # attribute, return it
249 attrs = dict(elem.attrib)
250 attrs['text'] = str(elem.text).strip()
251 attrs['parent'] = elem.getparent()
252 if isinstance(depth, int) and depth > 0:
253 for child_elem in list(elem):
254 key = str(child_elem.tag)
256 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
258 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
260 attrs['child_nodes'] = list(elem)
263 def merge(self, in_xml):
270 return etree.tostring(self.root.node, encoding='UTF-8', pretty_print=True)
272 # XXX smbaker, for record.load_from_string
273 def todict(self, elem=None):
277 d.update(elem.attrib)
278 d['text'] = elem.text
279 for child in elem.iterchildren():
280 if child.tag not in d:
282 d[child.tag].append(self.todict(child))
284 if len(d)==1 and ("text" in d):
289 def save(self, filename):
290 f = open(filename, 'w')
291 f.write(self.toxml())
295 #if __name__ == '__main__':
296 # rspec = RSpec('/tmp/resources.rspec')