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()

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com