Tod*_*nyo 3 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.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)
Run Code Online (Sandbox Code Playgroud)
这给了我想要的输出:
输出
<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>
Run Code Online (Sandbox Code Playgroud)
问题
为什么fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)]pre 周围需要 3 个大括号?
1 个大括号:{pre}导致 ValueError BAD
2 个大括号:在输出上{{pre}}产生BAD
3 个大括号:在输出上产生GOODns0:schemaLocation{{{pre}}}xsi:schemaLocation
我了解.format该字符串的用法,但我想了解为什么需要 3 个大括号。
命名空间属性名称的格式lxml为{namespace-uri}local-name. 因此xsi:schemaLocation,对于 ,您基本上想要添加带有名称的属性:
'{http://www.w3.org/2001/XMLSchema-instance}schemaLocation'
Run Code Online (Sandbox Code Playgroud)
该部分可以使用三重左大括号和右大括号来{namespace-uri}实现,可以读作:format()
{{:逃脱左大括号;输出文字{{pre}:占位符;xsi将被替换为中指定的变量值.format(pre=xsi) }}: 转义右大括号;输出文字}