您可以使用 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'))
您的 template.xml 文件:
<?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>