zoukankan      html  css  js  c++  java
  • Python学习---重点模块之xml

    xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单

    数据准备

     1 <?xml version="1.0"?>
     2 <data>
     3     <country name="Liechtenstein">
     4         <rank updated="yes">2</rank>
     5         <year>2008</year>
     6         <gdppc>141100</gdppc>
     7         <neighbor name="Austria" direction="E"/>
     8         <neighbor name="Switzerland" direction="W"/>
     9     </country>
    10     <country name="Singapore">
    11         <rank updated="yes">5</rank>
    12         <year>2011</year>
    13         <gdppc>59900</gdppc>
    14         <neighbor name="Malaysia" direction="N"/>
    15     </country>
    16     <country name="Panama">
    17         <rank updated="yes">69</rank>
    18         <year>2011</year>
    19         <gdppc>13600</gdppc>
    20         <neighbor name="Costa Rica" direction="W"/>
    21         <neighbor name="Colombia" direction="E"/>
    22     </country>
    23 </data>
    View Code

    读取xml

    import xml.etree.ElementTree as ET
    
    tree = ET.parse("hhh.xml")
    root = tree.getroot()
    print(root.tag)
    
    # 遍历xml文档
    for child in root:
        print(child.tag, child.attrib)
        for i in child:
            print(i.tag, i.text)
    
    # 只遍历year 节点
    for node in root.iter('year'):
        print(node.tag, node.text)
    # ---------------------------------------

    修改xml

    import xml.etree.ElementTree as ET
    
    tree = ET.parse("xmltest.xml")
    root = tree.getroot()
    
    # 修改
    for node in root.iter('year'):
        new_year = int(node.text) + 1
        node.text = str(new_year)
        node.set("updated", "yes")
    
    tree.write("xmltest.xml")

    删除xml

    # 删除node
    for country in root.findall('country'):
        rank = int(country.find('rank').text)
        if rank > 50:
            root.remove(country)
    
    tree.write('output.xml')

    创建XML

    import xml.etree.ElementTree as ET
    
    new_xml = ET.Element("namelist")
    name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
    age = ET.SubElement(name, "age", attrib={"checked": "no"})
    sex = ET.SubElement(name, "sex")
    sex.text = '33'
    name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
    age = ET.SubElement(name2, "age")
    age.text = '19'
    
    et = ET.ElementTree(new_xml)  # 生成文档对象
    et.write("test.xml", encoding="utf-8", xml_declaration=True)
    
    ET.dump(new_xml)  # 打印生成的格式
  • 相关阅读:
    没有被实例化的类 中的 非static成员函数竟然也可以被调用。。。前提是该成员函数没有用到成员变量
    c++注意
    关于类大小的小试验
    C语言|博客作业02
    在C#中进行时间和时间戳的转换
    正则表达式中匹配中括号 [ ]
    在C#中将对象序列化成Json格式
    在MSSQL中的简单数据类型递归
    HTML中padding和margin的区别和用法
    C#中的对称加密
  • 原文地址:https://www.cnblogs.com/ftl1012/p/xml.html
Copyright © 2011-2022 走看看