lxml ElementMaker属性格式

2024-10-01 02:38:24 发布

您现在位置:Python中文网/ 问答频道 /正文

多亏了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个大括号。在


Tags: orgformathttpfoowwwbar大括号pre
1条回答
网友
1楼 · 发布于 2024-10-01 02:38:24

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

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

{namespace-uri}部分可以使用format()和三个左右括号来实现,可以读作:

  • {{:转义的左大括号;输出文本{
  • {pre}:placeholder;将替换为xsi中指定的变量xsi的值
  • }}:转义的右大括号;输出文本}

相关问题 更多 >