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

猜你喜欢

转载自www.cnblogs.com/ylsd80/p/10341540.html
今日推荐