zoukankan      html  css  js  c++  java
  • 🍖xml 模块 (了解)

    本文来自 :https://www.cnblogs.com/yang1333/articles/12609714.html#3177870913

    1. XML文档模板

    <?xml version="1.0"?>
    <data>
        <country name="Liechtenstein">
            <rank updated="yes">2</rank>
            <year>2008</year>
            <gdppc>141100</gdppc>
            <neighbor name="Austria" direction="E"/>
            <neighbor name="Switzerland" direction="W"/>
        </country>
        <country name="Singapore">
            <rank updated="yes">5</rank>
            <year>2011</year>
            <gdppc>59900</gdppc>
            <neighbor name="Malaysia" direction="N"/>
        </country>
        <country name="Panama">
            <rank updated="yes">69</rank>
            <year>2011</year>
            <gdppc>13600</gdppc>
            <neighbor name="Costa Rica" direction="W"/>
            <neighbor name="Colombia" direction="E"/>
        </country>
    </data>
    

    2. 查看

    """
    # 注意: 返回值都是对应的标签节点对象.
    print(root.iter('year')) # 全文搜索
    print(root.find('country')) # 在root的子节点找,只找一个
    print(root.findall('country')) # 在root的子节点找,找所有(类始于subprocess中的找到所有sections)
    """
    import xml.etree.ElementTree as ET  # 这样导入的好处就是xml和etree包中的功能都能直接使用. 同时三者可以结合使用
    
    # 打开文件, 读出xml文件对象
    tree = ET.parse('db.xml')  # 如上xml模板存入db.xml文件中
    print(tree)  # <xml.etree.ElementTree.ElementTree object at 0x0000023703B24070>
    
    # 读出顶级节点对象date
    root = tree.getroot()
    print(root)  # <Element 'data' at 0x0000023703C7E720>
    
    # 查找三种方式
    # 1. 全文搜索: root.iter('year') 
    res = root.iter("year")
    print(res)  # <_elementtree._element_iterator object at 0x0000023EE649DE50>
    
    for year in res:
        print(''.center(50, '-'))
        print(year.tag)  # 获取year节点对象的标签名
        print(year.attrib)  # 获取year节点对象的属性. 以key:value对的形式输出. key代指属性名, value代指属性值
        print(year.text)  # 获取year节点对象中的文本内容.
    """
    --------------------------------------------------
    year
    {'update': 'no'}
    2018
    --------------------------------------------------
    year
    {'update': 'no'}
    2021
    --------------------------------------------------
    year
    {'update': 'no'}
    2021
    """
    
    # 2. 在root的子节点找,只找一个: root.find('country')
    res = root.find('country')
    print(res.tag)  # country
    print(res.attrib)  # {'name': 'Liechtenstein'}
    print(res.text)  # 文本内容为空
    
    # 递归查找country下的year. 并获取其标签名, 属性, 文本内容
    res = root.find('country').find('year')  # 等同于接着上面的继续, res.find('year')
    print(res)  # <Element 'year' at 0x000002A64D5BD590>
    print(res.tag)  # year
    print(res.attrib)  # {'update': 'no'}
    print(res.text)  # 2018
    
    # 3. 在root的子节点找所有: root.findall("country")
    res = root.findall("country")
    print(res)  # [<Element 'country' at 0x00000253D3A9E770>, <Element 'country' at 0x00000253D3ACD810>, <Element 'country' at 0x00000253D3ACDAE0>]
    
    for country in res:
        print(''.center(50, '-'))
        res = country.find('year')
        print(res.tag)
        print(res.attrib)
        print(res.text)
    '''
    --------------------------------------------------
    year
    {'update': 'no'}
    2018
    --------------------------------------------------
    year
    {'update': 'no'}
    2021
    --------------------------------------------------
    year
    {'update': 'no'}
    2021
    '''
    

    3. 修改

    import xml.etree.ElementTree as ET
    
    tree = ET.parse('db.xml')
    root = tree.getroot()
    
    # 需求: 把"db.xml"文件中的country所有year标签属性名改为no, 标签文本加10
    for year in root.iter('year'):
        print(year)
        year.text = str(int(year.text) + 10)  # 注意: "db.xml"使用year.text读出, 默认是字符串, 我们要使用int转换成整型才能进行数字运算.
        year.attrib = {'update': 'no'}
    
    tree.write('db.xml')
    
    # 需求:  把"db.xml"文件中的country下所有gdppc标签文本加10000
    for gdppc in root.iter('gdppc'):
        print(gdppc)
        gdppc.text = str(int(gdppc.text) + 10000)
    
    tree.write('db.xml')
    

    4. 增加

    import xml.etree.ElementTree as ET
    
    tree = ET.parse('db.xml')
    root = tree.getroot()
    
    for country in root.iter('country'):
        year = country.find("year")
        if int(year.text) > 2010:
            # 1. 调用ET.Element()方法增加标签, 属性, 文本
            flag = ET.Element('egon')  # 2. 添加标签
            flag.attrib = {'DSB': 'yes'} #  3. 为添加的flag标签对象添加属性
            flag.text = '大帅逼1'  # 4. 为添加的flag标签对象添加文本内容
            country.append(flag) # 5. 把添加的flag标签对象追加到country标签中, 作为country的子节点标签对象.(往country节点下添加子节点)
    
    tree.write("db.xml")
    

    5. 删除

    import xml.etree.ElementTree as ET
    
    tree = ET.parse('db.xml')
    root = tree.getroot()
    
    # 需求: 在所有的country标签节点对象下的rank如果它的文本内容大于50, 那么就删除这个country
    for country in root.findall('country'):
       rank = int(country.find('rank').text)
       if rank > 50:
         root.remove(country)
     
    tree.write('db.xml')
    

    6. 新建XML文档

    import xml.etree.ElementTree as ET
    
    new_xml = ET.Element("country")  # 创建标签country节点, 返回new_xml节点对象
    name = ET.SubElement(new_xml, "name", attrib={"update": "yes"})  # 在new_xml节点对象下创建标签名为"name"的子节点对象, 并指定属性
    name.text = 'egon'  # 为"name"字节的点对象添加文本内容
    age = ET.SubElement(new_xml, 'year', attrib={'update': 'no'})
    age.text = '18'
    sex = ET.SubElement(new_xml, 'sex')
    sex.text = 'male'
    
    et = ET.ElementTree(new_xml)  # 生成文档对象
    et.write('text.xml', encoding='utf-8', xml_declaration=True)  # 创建文件, 将该文档对象"et"写入. 
    
  • 相关阅读:
    Dos.ORM logo.Net轻量级开源ORM框架 Dos.ORM
    C# FUNC 应用
    WCF教程网址
    C#扩展方法实现 byte[] 输出为HEX字符串形式
    apache配置,禁止指定后缀访问
    IServerChannelSinkProvider
    在服务器端的远程对象中加上抽象工厂的接口和实现类
    pannel加载窗体
    权限框架
    工作周记
  • 原文地址:https://www.cnblogs.com/songhaixing/p/14275085.html
Copyright © 2011-2022 走看看