Search code examples
pythonxmlxml-generation

How to generate large XML file with "for" construction in Python without predefined structure?


I have 4000+ key-values records in REDIS. My XML file to server should be like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <string name="Address">Address</string>
     <string name="AppName">App</string>
</resources>

I need to generate XML file with all values I can get from DB (the number may be different). All examples I saw before were with pre-defined structure - it is always known in advance how many rows there will be. But in my case it is always different number. How to generate XML file "with cycle"?


Solution

  • You can use jinja2 :

     from jinja2 import Environment, PackageLoader, select_autoescape   
     import os
    
     def write_xml(list_data):
          env = Environment(
                   loader = PackageLoader('path', 'to', 'template', 'directory'),
                   autoescape = select_autoescape(['html', 'xml'])
                   )
          template = env.get_template('template.xml')
          output_from_parsed_template = template.render(values=list_data)
          path = os.path.join("path", "to", "output")
          with open(str(path), "wb+") as fh:
                fh.write(output_from_parsed_template.encode('utf-8'))
    

    Your template.xml file :

     <?xml version="1.0" encoding="utf-8"?>
         <resources>
           {% for value in values %}
             <string name="Address">{{ value.Address }}</string>
             <string name="AppName">{{ value.App }}</string>
           {% endfor %}
         </resources>