Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

Python reading xml

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...