Search code examples
pythonxmlelementtree

How to put xml tree into separate python file?


I use python and xml.etree.ElementTree for building a xml file. But only the base tree has more than 350 lines and I would like to put this in a seperate file. How do I do that?

My code:

import xml.etree.ElementTree as ET

***
mydata = ET.Element('root_data')
version = ET.SubElement(root_data, 'version')
date = ET.SubElement(root_data, 'date')
groups = ET.SubElement(root_data, 'groups')
group = ET.SubElement(groups, 'group')
templates = ET.SubElement(root_data, 'templates')
template = ET.SubElement(templates, 'template')
tpl_linked = ET.SubElement(template, 'template')
--- a lot more lines like this ---
***

So I would like to have the stuff between the *** in a separate file.

I tried to call it via a function, but that did not work because then the variables were not known in the main program.


Solution

  • xml.etree.ElementTree have a tree.write() function to file, see the documentation.

    import xml.etree.ElementTree as ET
    
    root_data = ET.Element('root_data') # corrected your code here
    version = ET.SubElement(root_data, 'version')
    date = ET.SubElement(root_data, 'date')
    groups = ET.SubElement(root_data, 'groups')
    group = ET.SubElement(groups, 'group')
    templates = ET.SubElement(root_data, 'templates')
    template = ET.SubElement(templates, 'template')
    tpl_linked = ET.SubElement(template, 'template')
    
    # For better format
    ET.indent(root_data, space='  ')
    ET.dump(root_data)
    
    # Write the tree to file
    tree = ET.ElementTree(root_data)
    tree.write('output_file.xml', encoding='utf-8', xml_declaration=True)
    

    Addition: Assume you have a file temp.py:

    import xml.etree.ElementTree as ET
    
    
    def xml_temp():
        root_data = ET.Element('root_data')
        version = ET.SubElement(root_data, 'version')
        date = ET.SubElement(root_data, 'date')
        groups = ET.SubElement(root_data, 'groups')
        group = ET.SubElement(groups, 'group')
        templates = ET.SubElement(root_data, 'templates')
        template = ET.SubElement(templates, 'template')
        tpl_linked = ET.SubElement(template, 'template')
        return root_data
    
    if __name__ == '__main__':
        xml_temp()
    

    This could be imported as other modules, read the modul documentation or packaging for more details. For example you have another python main file, e.g. xml_file.py:

    import xml.etree.ElementTree as ET
    from temp import xml_temp
    
    root = xml_temp()
    ET.indent(root, space='  ')
    ET.dump(root)
    

    Output:

    <root_data>
      <version />
      <date />
      <groups>
        <group />
      </groups>
      <templates>
        <template>
          <template />
        </template>
      </templates>
    </root_data>