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)  # 打印生成的格式
  • 相关阅读:
    每天一道算法题(13)——使用递归颠倒栈
    每天一道算法题(12)——和为n的连续正数序列或者随机数
    函数模板
    答题总结(1)
    顶点间最短路径长度之探寻算法
    最小生成树
    new与delete,malloc与free
    C++的继承与接口
    笔记13 AOP中After和AfterReturning的区别
    笔记12 注入AspectJ切面
  • 原文地址:https://www.cnblogs.com/ftl1012/p/xml.html
Copyright © 2011-2022 走看看