from lxml import etree from os import listdir from os.path import join, isdir root_dir = '../flattener_dicos' def xml_parse_document(document): families = document.xpath('variables/family') for family in families: if family.attrib['path'] == 'creole.containers': return family = etree.Element('family', hidden="True", icon="puzzle-piece", mode="expert", name="Containers", path="creole.containers") variable = etree.SubElement(family, 'variable', auto_freeze="False", auto_save="False", description="Bridge IP address", disabled="False", hidden="True", mandatory="False", mode="expert", multi="False", name="adresse_ip_br0", path="creole.containers.adresse_ip_br0", type="string") value = etree.SubElement(variable, 'value') value.text = '127.0.0.1' variable = etree.SubElement(family, 'variable', auto_freeze="False", auto_save="False", description="Bridge IP subnet mask", disabled="False", hidden="True", mandatory="False", mode="expert", multi="False", name="adresse_netmask_br0", path="creole.containers.adresse_netmask_br0", type="string") value = etree.SubElement(variable, 'value') value.text = '255.0.0.0' variable = etree.SubElement(family, 'variable', auto_freeze="False", auto_save="False", description="Bridge IP network_br0 address", disabled="False", hidden="True", mandatory="False", mode="expert", multi="False", name="adresse_network_br0", path="creole.containers.adresse_network_br0", type="string") value = etree.SubElement(variable, 'value') value.text = '127.0.0.0' variable = etree.SubElement(family, 'variable', auto_freeze="False", auto_save="False", description="Bridge broadcast IP address", disabled="False", hidden="True", mandatory="False", mode="expert", multi="False", name="adresse_broadcast_br0", path="creole.containers.adresse_broadcast_br0", type="string") value = etree.SubElement(variable, 'value') value.text = '127.255.255.255' elt = document.xpath('variables')[0] elt.insert(0, family) def edit(xmlfile): print('process {}'.format(xmlfile)) document = etree.parse(xmlfile).getroot() xml_parse_document(document) with file(xmlfile, 'w') as fh: fh.write(etree.tostring(document, pretty_print=True, encoding="UTF-8")) def main(): for xmldir in listdir(root_dir): xmldir = join(root_dir, xmldir) resultdir = join(xmldir, 'result') #if isdir(xmldir): # for dico in listdir(xmldir): # if dico.endswith('.xml'): # edit(join(xmldir, dico)) if isdir(resultdir): for dico in listdir(resultdir): if dico.endswith('.xml'): edit(join(resultdir, dico)) if __name__ == "__main__": main()