zoukankan      html  css  js  c++  java
  • python xml模块

    import xml.etree.ElementTree as ET
    
    # 生成XML
    new_xml = ET.Element('note')
    name = ET.SubElement(new_xml, 'to', attrib={'name': 'name'})
    name.text = 'George'
    from_node = ET.SubElement(new_xml, 'from')
    from_node.text = 'John'
    heading = ET.SubElement(new_xml, 'heading')
    heading.text = 'Reminder'
    body = ET.SubElement(new_xml, 'body')
    body.text = "Don't forget the meeting!"
    
    # 生成XML文件
    ET = ET.ElementTree(new_xml)
    ET.write('xml_test.xml', encoding='utf-8', xml_declaration=True)
    
    # 读取xml文件内容
    tree = ET.parse('xml_test.xml')
    root = tree.getroot()
    print(root)  # <Element 'note' at 0x02E69090>
    print(root.tag)  # note 标签名
    
    # 获取指定标签
    for i in root.iter('from'):
        print('标签名--》', i.tag)  # 标签名
        print('标属性--》', i.attrib)  # 标签属性
        print('标内容--》', i.text)  # 标签内容
    
    # 修改
    for i in root.iter('from'):
        i.text = i.text + '_new'  # 修改内容
        i.set('updated', 'yes')  # 修改属性
    
    # findall 查找全部标签   find 查找一个标签
    for heading in root.findall('heading'):
        print(heading.tag)
        # 删除标签
        root.remove(heading)
    
    tree.write('xml_new.xml')  # 写入处理后的xml到文件
  • 相关阅读:
    go-web摘抄1-基础知识
    arduino3-机械臂
    Arduino-2 使用按键开关
    Arduino-1 点亮小灯
    树莓派的语音识别
    gitlab的环境搭建及使用
    python数据处理 2
    idea 无法创建class文件
    Intellij IDEA添加database无法显示表等问题
    Intell idea 添加 jd反编译插件
  • 原文地址:https://www.cnblogs.com/kehaimin/p/11466798.html
Copyright © 2011-2022 走看看