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

 

相关文章:

  • 2021-07-31
  • 2022-02-07
  • 2021-11-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-30
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-10
  • 2021-10-28
  • 2022-01-30
  • 2021-12-05
相关资源
相似解决方案