2 from types import StringTypes
4 from StringIO import StringIO
6 from sfa.util.faults import InvalidXML
14 for (key, value) in filter.items():
19 if isinstance(value, str):
20 filter_list.append('%s="%s"' % (key, value))
21 elif isinstance(value, list):
22 filter_list.append('contains("%s", %s)' % (' '.join(map(str, value)), key))
24 xpath = ' and '.join(filter_list)
25 xpath = '[' + xpath + ']'
30 def __init__(self, xml=None):
32 self.namespaces = None
33 self.default_namespace = None
35 if isinstance(xml, basestring):
37 elif isinstance(xml, etree._ElementTree):
38 self.root = xml.getroot()
39 elif isinstance(xml, etree._Element):
42 def parse_xml(self, xml):
44 parse rspec into etree
46 parser = etree.XMLParser(remove_blank_text=True)
48 tree = etree.parse(xml, parser)
50 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
52 tree = etree.parse(StringIO(xml), parser)
54 raise InvalidXML(str(e))
55 self.root = tree.getroot()
57 self.namespaces = dict(self.root.nsmap)
58 if 'default' not in self.namespaces and None in self.namespaces:
59 # If the 'None' exist, then it's pointing to the default namespace. This makes
60 # it hard for us to write xpath queries for the default naemspace because lxml
61 # wont understand a None prefix. We will just associate the default namespeace
62 # with a key named 'default'.
63 self.namespaces['default'] = self.namespaces[None]
65 self.namespaces['default'] = 'default'
68 for key in self.root.attrib.keys():
69 if key.endswith('schemaLocation'):
70 # schema location should be at the end of the list
71 schema_parts = self.root.attrib[key].split(' ')
72 self.schema = schema_parts[1]
73 namespace, schema = schema_parts[0], schema_parts[1]
76 def parse_dict(self, d, root_tag_name='xml', element = None):
79 self.parse_xml('<%s/>' % root_tag_name)
86 # handle repeating fields
87 for (key, value) in d.items():
88 if isinstance(value, list):
91 if isinstance(val, dict):
92 child_element = etree.SubElement(element, key)
93 self.parse_dict(val, key, child_element)
94 elif isinstance(val, basestring):
95 child_element = etree.SubElement(element, key).text = val
97 elif isinstance(value, int):
98 d[key] = unicode(d[key])
102 # element.attrib.update will explode if DateTimes are in the
105 # looks like iteritems won't stand side-effects
107 if not isinstance(d[k],StringTypes):
110 element.attrib.update(d)
112 def validate(self, schema):
114 Validate against rng schema
116 relaxng_doc = etree.parse(schema)
117 relaxng = etree.RelaxNG(relaxng_doc)
118 if not relaxng(self.root):
119 error = relaxng.error_log.last_error
120 message = "%s (line %s)" % (error.message, error.line)
121 raise InvalidXML(message)
124 def xpath(self, xpath, namespaces=None):
126 namespaces = self.namespaces
127 return self.root.xpath(xpath, namespaces=namespaces)
129 def set(self, key, value):
130 return self.root.set(key, value)
132 def add_attribute(self, elem, name, value):
134 Add attribute to specified etree element
136 opt = etree.SubElement(elem, name)
139 def add_element(self, name, attrs={}, parent=None, text=""):
141 Wrapper around etree.SubElement(). Adds an element to
142 specified parent node. Adds element to root node is parent is
147 element = etree.SubElement(parent, name)
150 if isinstance(attrs, dict):
152 element.set(attr, attrs[attr])
155 def remove_attribute(self, elem, name, value):
157 Removes an attribute from an element
160 opts = elem.iterfind(name)
163 if opt.text == value:
166 def remove_element(self, element_name, root_node = None):
168 Removes all occurences of an element from the tree. Start at
169 specified root_node if specified, otherwise start at tree's root.
172 root_node = self.root
174 if not element_name.startswith('//'):
175 element_name = '//' + element_name
177 elements = root_node.xpath('%s ' % element_name, namespaces=self.namespaces)
178 for element in elements:
179 parent = element.getparent()
180 parent.remove(element)
182 def attributes_list(self, elem):
183 # convert a list of attribute tags into list of tuples
184 # (tagnme, text_value)
188 opts.append((e.tag, str(e.text).strip()))
191 def get_element_attributes(self, elem=None, depth=0):
193 elem = self.root_node
194 if not hasattr(elem, 'attrib'):
195 # this is probably not an element node with attribute. could be just and an
196 # attribute, return it
198 attrs = dict(elem.attrib)
199 attrs['text'] = str(elem.text).strip()
200 attrs['parent'] = elem.getparent()
201 if isinstance(depth, int) and depth > 0:
202 for child_elem in list(elem):
203 key = str(child_elem.tag)
205 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
207 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
209 attrs['child_nodes'] = list(elem)
212 def merge(self, in_xml):
219 return etree.tostring(self.root, encoding='UTF-8', pretty_print=True)
221 # XXX smbaker, for record.load_from_string
222 def todict(self, elem=None):
226 d.update(elem.attrib)
227 d['text'] = elem.text
228 for child in elem.iterchildren():
229 if child.tag not in d:
231 d[child.tag].append(self.todict(child))
233 if len(d)==1 and ("text" in d):
238 def save(self, filename):
239 f = open(filename, 'w')
240 f.write(self.toxml())
244 #if __name__ == '__main__':
245 # rspec = RSpec('/tmp/resources.rspec')