I have a list of string which I want to write in a XML file. My code looks like this :
from jinja2 import Environment, PackageLoader, select_autoescape
import os
env = Environment(loader = PackageLoader(path),
autoescape = select_autoescape(['html', 'xml']))
list_data = ['<managedObject class="test" operation="test"/>', '<managedObject class="test" operation="test"/>']
template = env.get_template('template.xml')
output_from_parsed_template = template.render(scripts=list_data)
path = os.path.join("output_file.xml")
with open(str(path), "wb") as fh:
fh.write(output_from_parsed_template.encode('utf-8'))
My template.xml looks like this :
<?xml version="1.0" encoding="UTF-8"?>
{% for script in scripts %}
{{ script }}
{% endfor %}
And I get the following error in the output_file.xml :
<?xml version="1.0" encoding="UTF-8"?>
<managedObject class="test" operation="test"/>
<managedObject class="test" operation="test"/>
Do you know how to write all special characters (double quotes and inf/supp sign) in the XML ? I'm using the same function to write a txt file and I don't have this problem.
Thanks for your help
{{ script | safe }}- this way Jinja puts XML/HTML as is - without converting to safer version which blocks hacker injections.autoescape=to put XML/HTML as is.