lxml ElementMaker 属性格式化

lxml ElementMaker Attribute formatting

感谢 this question/answer,我能够将名称空间属性添加到根元素。所以现在我有了这个:

代码

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)] 前面需要 3 个大括号?

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

上产生 xsi:schemaLocation

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

lxml中命名空间属性名称的格式为{namespace-uri}local-name。所以对于 xsi:schemaLocation,您基本上想要添加名称为:

的属性
'{http://www.w3.org/2001/XMLSchema-instance}schemaLocation'

{namespace-uri} 部分可以使用 format() 和三重开闭大括号来实现,可以读作:

  • {{:转义左大括号;输出文字 {
  • {pre}:占位符;将被 .format(pre=xsi)
  • 中指定的变量 xsi 的值替换
  • }}:转义右大括号;输出文字 }