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

    import xml.etree.ElementTree as ET
    
    
    tree = ET.parse('20200111142206.xml')#parse解析
    root = tree.getroot()#获取根
    print(root.find('object').find('bndbox').find('xmin'))
    print(root.tag)#打印标签名
    
    #遍历xml文档
    def bianli(root):
        for i in root:
            # print(i)
            print(i.tag,i.attrib) #打印标签名和属性值
            for j in i:
                print(j.tag,j.attrib,j.text) #j.text是标签内容
    
    #遍历特定节点
    def bianli2(root):
        for i in root.iter('width'):
            print(i.tag,i.text)
    
    #修改
    def change(root):
        for node in root.iter('width'):
            new_width = int(node.text) + 1 #值+1
            node.text = str(new_width)
            node.set("updated",'yes')#增加属性
    
    #删除
    def delete_node(root):
        for node in root.findall('object'):
            node1 = node.find('bndbox')
            node2 = node1.find('xmin')
            value = int(node2.text)#只能一层层的找
            print(value)
            if value > 50:
                node1.remove(node2)#不能越级删除   root.remove(node2)#无法删除
    
    #创建
    def creat_xml():
        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")
        age.text = '19'
        sex.text = '33'
    
        name2 = ET.SubElement(new_xml, 'name', attrib={"enrolled": "yes"})
        age = ET.SubElement(name2, 'age', attrib={"checked": "no"})
        sex = ET.SubElement(name2, "sex")
        age.text = '22'
        sex.text = '44'
    
        et = ET.ElementTree(new_xml)
        et.write('new_xml',encoding='utf-8',xml_declaration=True)
    
    # change(root)
    # delete_node(root)
    # tree.write('abc.xml')#写新的tree
    creat_xml()
  • 相关阅读:
    [asp.net core]SignalR一个例子
    [Asp.net core]bootstrap分页
    ${pageContext.request.contextPath}无法解析
    [Java web]Spring+Struts2+Hibernate整合过程(2)
    [Java web]Spring+Struts2+Hibernate整合过程
    java.lang.IllegalStateException: Failed to load ApplicationContext
    [Struts2]配置文件
    unihtmlmemo使用
    ADO序列
    variant和rawbytestring相互转换
  • 原文地址:https://www.cnblogs.com/Manuel/p/12672864.html
Copyright © 2011-2022 走看看