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

 

posted on 2020-04-10 13:18  Manuel  阅读(180)  评论(0编辑  收藏  举报