码迷,mamicode.com
首页 > 其他好文 > 详细

xml模块

时间:2020-04-10 13:30:10      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:签名   checked   src   port   let   upd   rem   attr   修改   

 

 

技术图片

 

 

 

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()

 

xml模块

标签:签名   checked   src   port   let   upd   rem   attr   修改   

原文地址:https://www.cnblogs.com/Manuel/p/12672864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!