X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=sfa%2Futil%2Fxml.py;h=a1a6fa347f2c4d694f8e965a295a2611a7fc2fc1;hb=57b6a99255d4a88be9c0f910f8524677e34ff4bc;hp=5a2656c21602b00501243ee6ff9921aeee840ee9;hpb=b8fa26126b5d9c1680655c6dfa4faffd18ad0530;p=sfa.git diff --git a/sfa/util/xml.py b/sfa/util/xml.py index 5a2656c2..a1a6fa34 100755 --- a/sfa/util/xml.py +++ b/sfa/util/xml.py @@ -1,10 +1,8 @@ #!/usr/bin/python from lxml import etree from StringIO import StringIO -from datetime import datetime, timedelta -from sfa.util.xrn import * -from sfa.util.plxrn import hostname_to_urn -from sfa.util.faults import SfaNotImplemented, InvalidXML + +from sfa.util.faults import InvalidXML class XpathFilter: @staticmethod @@ -56,6 +54,8 @@ class XML: self.root = tree.getroot() # set namespaces map self.namespaces = dict(self.root.nsmap) + if 'default' not in self.namespaces and None in self.namespaces: + self.namespaces['default'] = self.namespaces[None] # If the 'None' exist, then it's pointing to the default namespace. This makes # it hard for us to write xpath queries for the default naemspace because lxml # wont understand a None prefix. We will just associate the default namespeace @@ -73,6 +73,26 @@ class XML: namespace, schema = schema_parts[0], schema_parts[1] break + def parse_dict(self, d, root_tag_name='xml', element = None): + if element is None: + self.parse_xml('<%s/>' % root_tag_name) + element = self.root + + if 'text' in d: + text = d.pop('text') + element.text = text + + # handle repeating fields + for (key, value) in d.items(): + if isinstance(value, list): + value = d.pop(key) + for val in value: + if isinstance(val, dict): + child_element = etree.SubElement(element, key) + self.parse_dict(val, key, child_element) + + element.attrib.update(d) + def validate(self, schema): """ Validate against rng schema @@ -180,14 +200,27 @@ class XML: return self.toxml() def toxml(self): - return etree.tostring(self.root, pretty_print=True) + return etree.tostring(self.root, encoding='UTF-8', pretty_print=True) + + def todict(self, elem=None): + if elem is None: + elem = self.root + d = {} + d.update(elem.attrib) + d['text'] = elem.text + for child in elem.iterchildren(): + if child.tag not in d: + d[child.tag] = [] + d[child.tag].append(self.todict(child)) + return d def save(self, filename): f = open(filename, 'w') f.write(self.toxml()) f.close() - -if __name__ == '__main__': - rspec = RSpec('/tmp/resources.rspec') - print rspec + +# no RSpec in scope +#if __name__ == '__main__': +# rspec = RSpec('/tmp/resources.rspec') +# print rspec