多亏了this问题/答案,我能够将名称空间属性添加到根元素中。现在我有了这个:
代码
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)
这给了我想要的输出:
输出
^{pr2}$问题
为什么fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)]
在pre的前后需要3个大括号?在
1大括号:{pre}
导致值错误错误
2个大括号:{{pre}}
在输出上产生ns0:schemaLocation
坏的
3个大括号:{{{pre}}}
在输出上产生{
我了解字符串的.format
用法,但我想知道为什么我需要3个大括号。在
lxml
中命名空间属性名的格式是{namespace-uri}local-name
。所以对于xsi:schemaLocation
,您基本上想添加名为的属性:{namespace-uri}
部分可以使用format()
和三个左右括号来实现,可以读作:{{
:转义的左大括号;输出文本{
{pre}
:placeholder;将替换为xsi
中指定的变量xsi
的值}}
:转义的右大括号;输出文本}
相关问题 更多 >
编程相关推荐