3 from StringIO import StringIO
5 from sfa.util.faults import InvalidXML
13 for (key, value) in filter.items():
18 if isinstance(value, str):
19 filter_list.append('%s="%s"' % (key, value))
20 elif isinstance(value, list):
21 filter_list.append('contains("%s", %s)' % (' '.join(map(str, value)), key))
23 xpath = ' and '.join(filter_list)
24 xpath = '[' + xpath + ']'
29 def __init__(self, xml=None):
31 self.namespaces = None
32 self.default_namespace = None
34 if isinstance(xml, basestring):
36 elif isinstance(xml, etree._ElementTree):
37 self.root = xml.getroot()
38 elif isinstance(xml, etree._Element):
41 def parse_xml(self, xml):
43 parse rspec into etree
45 parser = etree.XMLParser(remove_blank_text=True)
47 tree = etree.parse(xml, parser)
49 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
51 tree = etree.parse(StringIO(xml), parser)
53 raise InvalidXML(str(e))
54 self.root = tree.getroot()
56 self.namespaces = dict(self.root.nsmap)
57 if 'default' not in self.namespaces and None in self.namespaces:
58 # If the 'None' exist, then it's pointing to the default namespace. This makes
59 # it hard for us to write xpath queries for the default naemspace because lxml
60 # wont understand a None prefix. We will just associate the default namespeace
61 # with a key named 'default'.
62 self.namespaces['default'] = self.namespaces[None]
64 self.namespaces['default'] = 'default'
67 for key in self.root.attrib.keys():
68 if key.endswith('schemaLocation'):
69 # schema location should be at the end of the list
70 schema_parts = self.root.attrib[key].split(' ')
71 self.schema = schema_parts[1]
72 namespace, schema = schema_parts[0], schema_parts[1]
75 def parse_dict(self, d, root_tag_name='xml', element = None):
78 self.parse_xml('<%s/>' % root_tag_name)
85 # handle repeating fields
86 for (key, value) in d.items():
87 if isinstance(value, list):
90 if isinstance(val, dict):
91 child_element = etree.SubElement(element, key)
92 self.parse_dict(val, key, child_element)
93 elif isinstance(val, basestring):
94 child_element = etree.SubElement(element, key).text = val
96 elif isinstance(value, int):
97 d[key] = unicode(d[key])
101 element.attrib.update(d)
103 def validate(self, schema):
105 Validate against rng schema
107 relaxng_doc = etree.parse(schema)
108 relaxng = etree.RelaxNG(relaxng_doc)
109 if not relaxng(self.root):
110 error = relaxng.error_log.last_error
111 message = "%s (line %s)" % (error.message, error.line)
112 raise InvalidXML(message)
115 def xpath(self, xpath, namespaces=None):
117 namespaces = self.namespaces
118 return self.root.xpath(xpath, namespaces=namespaces)
120 def set(self, key, value):
121 return self.root.set(key, value)
123 def add_attribute(self, elem, name, value):
125 Add attribute to specified etree element
127 opt = etree.SubElement(elem, name)
130 def add_element(self, name, attrs={}, parent=None, text=""):
132 Generic wrapper around etree.SubElement(). Adds an element to
133 specified parent node. Adds element to root node is parent is
138 element = etree.SubElement(parent, name)
141 if isinstance(attrs, dict):
143 element.set(attr, attrs[attr])
146 def remove_attribute(self, elem, name, value):
148 Removes an attribute from an element
151 opts = elem.iterfind(name)
154 if opt.text == value:
157 def remove_element(self, element_name, root_node = None):
159 Removes all occurences of an element from the tree. Start at
160 specified root_node if specified, otherwise start at tree's root.
163 root_node = self.root
165 if not element_name.startswith('//'):
166 element_name = '//' + element_name
168 elements = root_node.xpath('%s ' % element_name, namespaces=self.namespaces)
169 for element in elements:
170 parent = element.getparent()
171 parent.remove(element)
173 def attributes_list(self, elem):
174 # convert a list of attribute tags into list of tuples
175 # (tagnme, text_value)
179 opts.append((e.tag, str(e.text).strip()))
182 def get_element_attributes(self, elem=None, depth=0):
184 elem = self.root_node
185 if not hasattr(elem, 'attrib'):
186 # this is probably not an element node with attribute. could be just and an
187 # attribute, return it
189 attrs = dict(elem.attrib)
190 attrs['text'] = str(elem.text).strip()
191 attrs['parent'] = elem.getparent()
192 if isinstance(depth, int) and depth > 0:
193 for child_elem in list(elem):
194 key = str(child_elem.tag)
196 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
198 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
200 attrs['child_nodes'] = list(elem)
203 def merge(self, in_xml):
210 return etree.tostring(self.root, encoding='UTF-8', pretty_print=True)
212 def todict(self, elem=None):
216 d.update(elem.attrib)
217 d['text'] = elem.text
218 for child in elem.iterchildren():
219 if child.tag not in d:
221 d[child.tag].append(self.todict(child))
224 def save(self, filename):
225 f = open(filename, 'w')
226 f.write(self.toxml())
230 #if __name__ == '__main__':
231 # rspec = RSpec('/tmp/resources.rspec')