我的目标是构建一个带有可变属性占位符的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>
有什么想法吗?感谢。
答案 0 :(得分:4)
要在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。
答案 1 :(得分:3)
您的模板需要大括号:
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="Michael" age="10" dob="15/10/1900"/>
</others:sequence>
</personal>
format method替换花括号中的名称。比较,例如,
In [20]: 'cheese'.format(cheese='Roquefort')
Out[20]: 'cheese'
In [21]: '{cheese}'.format(cheese='Roquefort')
Out[21]: 'Roquefort'
我看到你有lxml
。优秀。在这种情况下,你可以use lxml.builder
to construct XML。这将有助于您创建有效的XML:
import lxml.etree as ET
import lxml.builder as builder
E = builder.E
F = builder.ElementMaker(namespace='http://foo', nsmap={'others':'http://foo'})
x = 2*5
xmlTemplate = ET.tostring(F.root(
E.personal(
F.sequence(
E.feature(name='Michael',
age=str(x),
dob='15/10/1900')
), reference="500.txt")),
pretty_print=True)
print(xmlTemplate)
产量
<others:root xmlns:other="http://foo">
<personal reference="500.txt">
<others:sequence>
<feature dob="15/10/1900" age="10" name="Michael"/>
</others:sequence>
</personal>
</others:root>
这个字符串可以通过lxml使用:
进行解析doc = ET.fromstring(xmlTemplate)
print(doc)
# <Element {http://foo}root at 0xb741866c>