由于这个问题/答案,我能够将命名空间属性添加到根元素中。所以现在我有了:
代码
from lxml.builder import ElementMaker
foo = 'http://www.foo.org/XMLSchema/bar'
xsi = 'http://www.w3.org/2001/XMLSchema-instance'
E = ElementMaker(namespace=foo, nsmap={'foo': foo, 'xsi': xsi})
fooroot = E.component()
fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)] = 'http://www.foo.org/XMLSchema/bar http://www.foo.org/XMLSchema/barindex.xsd'
bars = E.bars(label='why?', validates='required')
fooroot.append(bars)
bars.append(E.bar(label='Image1'))
bars.append(E.bar(label='Image2'))
etree.dump(fooroot)
这给了我所需的输出:
输出
<foo:component xmlns:foo="http://www.foo.org/XMLSchema/bar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.foo.org/XMLSchema/bar http://www.foo.org/XMLSchema/barindex.xsd">
<foo:bars label="why?" validates="required">
<foo:bar label="Image1"/>
<foo:bar label="Image2"/>
</foo:bars>
</foo:component>
问题
为什么fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)]
在PRE?
1个撑杆: 我了解字符串的{pre}
导致ValueError 坏
2个括号:{{pre}}
在输出 BAD
上产生ns0:schemaLocation
3个括号:{{{pre}}}
在输出上产生xsi:schemaLocation
.format
使用率,但是我想了解为什么需要3个括号。
lxml
中名称名称的格式为 {namespace-uri}local-name
。因此,对于xsi:schemaLocation
,您基本上想添加名称:
'{http://www.w3.org/2001/XMLSchema-instance}schemaLocation'
可以使用format()
和三重开口和闭合括号来实现{namespace-uri}
零件,可以读为:
-
{{
:逃脱的开口括号;输出字面的{
-
{pre}
:占位符;将被.format(pre=xsi)
中指定的可变xsi
的值替换 -
}}
:逃脱的闭合牙套;输出字面的}