Python lxml ElementMaker属性格式

Python lxml ElementMaker属性格式,python,attributes,lxml,Python,Attributes,Lxml,多亏了问答,我才能够将名称空间属性添加到根元素中。现在我有了这个: 代码 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.compon

多亏了问答,我才能够将名称空间属性添加到根元素中。现在我有了这个:

代码

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)
这将为我提供所需的输出:

输出


问题

为什么
foooot.attrib[{{{{pre}}}}schemaLocation.format(pre=xsi)]
需要在pre周围加上3个大括号

1大括号:
{pre}
导致ValueError错误
2个大括号:
{{pre}
在输出上产生
ns0:schemaLocation
BAD
3个大括号:
{{{pre}}
在输出上生成
xsi:schemaLocation
GOOD


我了解字符串的
.format
用法,但我想了解为什么我需要3个大括号。

lxml中命名空间属性名的格式是
{namespace uri}local name
。因此,对于
xsi:schemaLocation
,您基本上希望添加名为:

'{http://www.w3.org/2001/XMLSchema-instance}schemaLocation'
{namespace uri}
部分可以使用
format()
和三个大括号(可以理解为:

  • {{
    :转义的大括号;输出文字
    {
  • {pre}
    :占位符;将替换为
    格式(pre=xsi)
  • }
    :转义的右大括号;输出文字
    }

谢谢你的猜测,我没有像我应该理解的那样理解
.format
语法。我想我没有像我应该理解的那样理解
.format
语法。
'{http://www.w3.org/2001/XMLSchema-instance}schemaLocation'