簡體   English   中英

寫入 XML Python - 字符串列表中的特殊字符錯誤

[英]Write XML Python - Special characters error in list of string

我有一個要寫入 XML 文件的字符串列表。 我的代碼如下所示:

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'))

我的 template.xml 看起來像這樣:

<?xml version="1.0" encoding="UTF-8"?>
{% for script in scripts %}
     {{ script }}
{% endfor %}

我在 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;

您知道如何在 XML 中寫入所有特殊字符(雙引號和 inf/supp 符號)嗎? 我正在使用相同的function來寫一個txt文件,我沒有這個問題。

謝謝你的幫助

問題不在於書寫,而是在 Jinja 中自動轉義。

你必須使用

 {{ script | safe }}

在沒有自動轉義的情況下放置 XML/HTML。

或者從代碼中刪除行autoescape=select_autoescape(['html', 'xml'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM