zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    2021.4.2 Python基础及介绍
    2021.4.1 团队组队
    冲击信号
    信号卷积(线性卷积)
    数字图像处理基本概念
    计算机视觉发展及主要研究方向
    SVM 之 SMO 算法
    FP Growth 算法
    Apriori 算法
    26 实战页式内存管理 下
  • 原文地址:https://www.cnblogs.com/ylsd80/p/10341540.html
Copyright © 2011-2022 走看看