python - Change default namespace of subelement in lxml -


i want generate xml lxml:

<aroot xmlns="http://a/">   <broot xmlns="http://b/" xmlns:a="http://a/">     <child1/>     <child2/>     <a:smalltag1/>     <a:smalltag2/>   </broot> </aroot> 

but following code (that seems correct output), not generates above xml.

from lxml import etree lxml.builder import elementmaker  ns_a = 'http://a/' ns_b = 'http://b/'  = elementmaker(namespace=ns_a, nsmap={none: ns_a, 'b': ns_b}) b = elementmaker(namespace=ns_b, nsmap={none: ns_b, 'a': ns_a})  elem = a.aroot(     b.broot(         b.child1,         b.child2,         a.smalltag1,         a.smalltag2,     ), )  print(etree.tostring(elem, pretty_print=true).decode('ascii')) 

this generates:

<aroot xmlns:b="http://b/" xmlns="http://a/">   <b:broot>     <b:child1/>     <b:child2/>     <smalltag1/>     <smalltag1/>   </b:broot> </aroot> 

this valid xml, cannot change default namespace on subelemnt broot.

if change a elementmaker following:

a = elementmaker(namespace=ns_a, nsmap={none: ns_a}) 

the output becomes:

<aroot xmlns="http://a/">   <broot xmlns="http://b/">     <child1/>     <child2/>     <smalltag1/>     <smalltag2/>   </broot> </aroot> 

which invalid xml (namespace of smalltag1 b)

and if change both a , b follows:

a = elementmaker(namespace=ns_a, nsmap={none: ns_a}) b = elementmaker(namespace=ns_b, nsmap={none: ns_b}) 

the output is:

<aroot xmlns="http://a/">   <broot xmlns="http://b/">     <child1/>     <child2/>     <smalltag1 xmlns="http://a/"/>     <smalltag2 xmlns="http://a/"/>   </broot> </aroot> 

which valid, not desired output.

using etree:

from lxml import etree  ns_a = 'http://a/' ns_b = 'http://b/'  aroot = element('{%s}aroot' % (ns_a), nsmap={none: ns_a}) broot = etree.subelement(aroot, '{%s}broot' % (ns_b), nsmap={none: ns_b, 'a': ns_a}) etree.subelement(broot, '{%s}child1' % (ns_b)) etree.subelement(broot, '{%s}child2' % (ns_b)) etree.subelement(broot, '{%s}smalltag1' % (ns_a)) etree.subelement(broot, '{%s}smalltag2' % (ns_a))  print etree.tostring(aroot, pretty_print=true) 

you get:

<aroot xmlns="http://a/">   <broot xmlns:a="http://a/" xmlns="http://b/">     <child1/>     <child2/>     <a:smalltag1/>     <a:smalltag2/>   </broot> </aroot> 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -