python的xml讀取庫etree


from xml.etree import ElementTree


data = '''<?xml version="1.0" encoding="UTF-8"?>
    <data>
        <country name="Liechtenstein">
            <rank>1</rank>
            <year>2008</year>
            <gdppc>141100</gdppc>
            <neighbor name="Austria" direction="E"/>
            <neighbor name="Switzerland" direction="W"/>
        </country>
    </data>'''


# 遍歷xml結構內容
tree = ElementTree.fromstring(data)
print(type(tree))
for childa in tree:
    print(childa.tag,childa.text,childa.attrib)
    for child in childa:
        print(child.tag,child.text,child.attrib)


print("%s"% "*"*60)
#查找指定的tag名稱
for rank in tree.iter("rank"):
    print(rank.tag,rank.text)

for country in tree.findall("country"):
    rank = country.find("rank").text
    name = country.get("name")
    print(name,rank)

print("%s"% "*"*60)
#修改xml文件
for rank in tree.iter("rank"):
    new_rank = int(rank.text) + 10
    rank.text = str(new_rank)
    rank.set("updated","yes")
#寫入文件
f = open("output.xml","wb")
f.write(ElementTree.tostring(tree))
f.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM