0

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"?>
&lt;managedObject class=&#34;test&#34; operation=&#34;test&#34;/&gt;

&lt;managedObject class=&#34;test&#34; operation=&#34;test&#34;/&gt;

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

2
  • {{ script | safe }} - this way Jinja puts XML/HTML as is - without converting to safer version which blocks hacker injections. Commented Jun 4, 2020 at 10:29
  • or maybe you should remove autoescape= to put XML/HTML as is. Commented Jun 4, 2020 at 10:47

1 Answer 1

1

Problem is not writing but autoescaping in Jinja.

You have to use

 {{ script | safe }}

to put XML/HTML without autoescaping.

Or remove line autoescape=select_autoescape(['html', 'xml']) from code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.