3 from StringIO import StringIO
4 from datetime import datetime, timedelta
5 from sfa.util.xrn import *
6 from sfa.util.plxrn import hostname_to_urn
7 from sfa.util.faults import SfaNotImplemented, InvalidXML
15 for (key, value) in filter.items():
20 if isinstance(value, str):
21 filter_list.append('%s="%s"' % (key, value))
22 elif isinstance(value, list):
23 filter_list.append('contains("%s", %s)' % (' '.join(map(str, value)), key))
25 xpath = ' and '.join(filter_list)
26 xpath = '[' + xpath + ']'
31 def __init__(self, xml=None):
33 self.namespaces = None
34 self.default_namespace = None
36 if isinstance(xml, basestring):
38 elif isinstance(xml, etree._ElementTree):
39 self.root = xml.getroot()
40 elif isinstance(xml, etree._Element):
43 def parse_xml(self, xml):
45 parse rspec into etree
47 parser = etree.XMLParser(remove_blank_text=True)
49 tree = etree.parse(xml, parser)
51 # 'rspec' file doesnt exist. 'rspec' is proably an xml string
53 tree = etree.parse(StringIO(xml), parser)
55 raise InvalidXML(str(e))
56 self.root = tree.getroot()
58 self.namespaces = dict(self.root.nsmap)
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 if None in self.namespaces:
64 default_namespace = self.namespaces.pop(None)
65 self.namespaces['default'] = default_namespace
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):
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)
94 element.attrib.update(d)
96 def validate(self, schema):
98 Validate against rng schema
100 relaxng_doc = etree.parse(schema)
101 relaxng = etree.RelaxNG(relaxng_doc)
102 if not relaxng(self.root):
103 error = relaxng.error_log.last_error
104 message = "%s (line %s)" % (error.message, error.line)
105 raise InvalidXML(message)
108 def xpath(self, xpath, namespaces=None):
110 namespaces = self.namespaces
111 return self.root.xpath(xpath, namespaces=namespaces)
113 def set(self, key, value):
114 return self.root.set(key, value)
116 def add_attribute(self, elem, name, value):
118 Add attribute to specified etree element
120 opt = etree.SubElement(elem, name)
123 def add_element(self, name, attrs={}, parent=None, text=""):
125 Generic wrapper around etree.SubElement(). Adds an element to
126 specified parent node. Adds element to root node is parent is
131 element = etree.SubElement(parent, name)
134 if isinstance(attrs, dict):
136 element.set(attr, attrs[attr])
139 def remove_attribute(self, elem, name, value):
141 Removes an attribute from an element
144 opts = elem.iterfind(name)
147 if opt.text == value:
150 def remove_element(self, element_name, root_node = None):
152 Removes all occurences of an element from the tree. Start at
153 specified root_node if specified, otherwise start at tree's root.
156 root_node = self.root
158 if not element_name.startswith('//'):
159 element_name = '//' + element_name
161 elements = root_node.xpath('%s ' % element_name, namespaces=self.namespaces)
162 for element in elements:
163 parent = element.getparent()
164 parent.remove(element)
166 def attributes_list(self, elem):
167 # convert a list of attribute tags into list of tuples
168 # (tagnme, text_value)
172 opts.append((e.tag, str(e.text).strip()))
175 def get_element_attributes(self, elem=None, depth=0):
177 elem = self.root_node
178 if not hasattr(elem, 'attrib'):
179 # this is probably not an element node with attribute. could be just and an
180 # attribute, return it
182 attrs = dict(elem.attrib)
183 attrs['text'] = str(elem.text).strip()
184 attrs['parent'] = elem.getparent()
185 if isinstance(depth, int) and depth > 0:
186 for child_elem in list(elem):
187 key = str(child_elem.tag)
189 attrs[key] = [self.get_element_attributes(child_elem, depth-1)]
191 attrs[key].append(self.get_element_attributes(child_elem, depth-1))
193 attrs['child_nodes'] = list(elem)
196 def merge(self, in_xml):
203 return etree.tostring(self.root, pretty_print=True)
205 def todict(self, elem=None):
209 d.update(elem.attrib)
210 d['text'] = elem.text
211 for child in elem.iterchildren():
212 if child.tag not in d:
214 d[child.tag].append(self.todict(child))
217 def save(self, filename):
218 f = open(filename, 'w')
219 f.write(self.toxml())
222 if __name__ == '__main__':
223 rspec = RSpec('/tmp/resources.rspec')