Merci à este question/réponse, j'ai pu faire ajouter un attribut namespace à un élément Root. J'ai donc maintenant ceci :
Code
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)
Cela me donne le résultat souhaité :
Sortie
<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>
La question
Pourquoi le fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)]
nécessite 3 attaches autour du pré ?
1 accolade : {pre}
provoque une ValueError MAUVAIS
2 accolades : {{pre}}
produit ns0:schemaLocation
sur la sortie MAUVAIS
3 accolades : {{{pre}}}
produit xsi:schemaLocation
sur la sortie BON
Je comprends que .format
usage pour la chaîne, mais j'aimerais comprendre pourquoi j'ai besoin de 3 accolades.