Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
228 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 etree

tree = 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...