我的目标是构建一个带有变量属性占位符的 xml 模板。由于某些原因,该模板不会将新数据放入其占位符中。
这是一个例子:
x=2*5
xmlTemplate="""
<personal reference="500.txt">
<others:sequence>
<feature:name="name" age="age" dob="dob"/>
</others:sequence>
</personal>""".format(name='Michael', age=x, dob=15/10/1900)
print xmlTemplate
输出:
<personal reference="500.txt">
<others:sequence>
<feature:name="name" age="age" dob="dob"/>
</others:sequence>
</personal>
理想输出:
<personal reference="500.txt">
<others:sequence>
<feature:name="Michael" age="10" dob="15/10/1900"/>
</others:sequence>
</personal>
有什么想法吗?谢谢。
最佳答案
要在 Python 中创建 XML 文档,使用 Yattag 似乎更容易图书馆。
from yattag import Doc
doc, tag, text = Doc().tagtext()
x = 2*5
with tag('personal', reference = "500.txt"):
with tag('others:sequence'):
doc.stag('feature', name = "Michael", age = str(x), dob = "15/10/1900")
print(doc.getvalue())
运行时,上面的代码会生成如下的XML:
<personal reference="500.txt">
<others:sequence>
<feature name="Michael" age="10" dob="15/10/1900" />
</others:sequence>
</personal>
注意:为提高可读性,在上面的示例中添加了缩进,因为 getvalue
返回标签之间没有空格的单行。要生成格式化文档,use the indent
function .
关于python - 如何从头开始构建具有可变属性的xml模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22897329/