1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
from lxml import etree
import types
xml_string = '''<?xml version='1.0' encoding='UTF-8'?>
<backups_db>
<backup id='1' name='Photos'>
<location type="file">/home/user/maphoto.jpg</location>
<location type="dir">/home/user/Photos</location>
</backup>
<backup id='2' name='Vidéos'>
<location type="file">/home/user/a\ trier/vacances.mkv</location>
<location type="dir">/home/user/Vidéos</location>
<location type="file">/home/user/montage.ogm</location>
</backup>
</backups_db>'''
class XMLProxy(object):
def __init__(self, file):
object.__init__(self)
self.file = file
self.root = etree.XML(self.file)
def read_xml(self):
return self.__read_xml(self.root)
def __read_xml(self, root):
obj = dic_str_to_class[root.tag.capitalize()]()
for attribute in root.attrib:
obj.__setattr__(attribute.capitalize(), root.attrib[attribute])
if(len(root) == 0):
obj.__setattr__("Value", root.text)
else:
children = []
for child in root:
children.append(self.__read_xml(child))
if(len(children) > 0):
obj.__setattr__(children[0].__class__.__name__.capitalize()+"s", children)
return obj
def write(self, obj, output_file):
elt = self.__write(obj)
elt_tree = etree.ElementTree(elt)
return elt
def __write(self, obj):
tag = obj.__class__.__name__.lower()
attributes = {}
children = None
value = None
for name in self.get_xml_variables(obj):
if(isinstance(obj.__getattribute__(name), types.ListType)):
children = obj.__getattribute__(name)
else:
attributes[name.lower()] = obj.__getattribute__(name)
if(attributes.has_key("value")):
value = attributes["value"]
attributes.__delitem__("value")
if(value != None and children != None):
print("Erreur XMLProxy.write() : value et children != None")
sys.exit(2)
elt = etree.Element(tag, attributes)
if(value != None):
elt.text = value
elif(children != None):
for child in children:
elt.append(self.__write(child))
return elt
def get_xml_variables(self, obj):
for var in dir(obj):
if(var[0] != '_' and var == var.capitalize()):
yield var
class Backups_db(object):
def __init__(self):
object.__init__(self)
class Backup(object):
def __init__(self):
object.__init__(self)
class Location(object):
def __init__(self):
object.__init__(self)
dic_str_to_class = { "Backups_db" : Backups_db,"Backup": Backup, "Location" : Location }
if __name__ == "__main__":
xmlproxy = XMLProxy(xml_string)
obj = xmlproxy.read_xml()
xml_element = xmlproxy.write(obj, "file2.xml")
print(etree.tostring(xml_element, pretty_print=True, encoding=unicode)) |
Partager