I am newbie on Python programming. I have requirement where I need to read the xml structure and build the new soap request xml by adding namespace like here is the example what I have
Below XML which i get from other system:
<foo><bar><type foobar="1"/><type foobar="2"/></bar>
</foo>
I want final result like below
<?xml version="1.0"?>
<soa:foo xmlns:soa="https://www.w3schools.com/furniture"><soa:bar><soa:type foobar="1"/><soa:type foobar="2"/></soa:bar>
</soa:foo>
I tried to look in python document but not able to find
One option is to use lxml to iterate over all of the elements and add the namespace uri to the .tag
property.
You can use register_namespace()
to bind the uri to the desired prefix.
Example...
from lxml import etreetree = etree.parse("input.xml")etree.register_namespace("soa", "https://www.w3schools.com/furniture")for elem in tree.iter():elem.tag = f"{{https://www.w3schools.com/furniture}}{elem.tag}"print(etree.tostring(tree, pretty_print=True).decode())
Printed output...
<soa:foo xmlns:soa="https://www.w3schools.com/furniture"><soa:bar><soa:type foobar="1"/><soa:type foobar="2"/></soa:bar>
</soa:foo>