python xml读写

1. xml例子


  VOC2007
  01240001.jpg
  
  
    like
    Unspecified
    
      211
      152
      239
      194
    
  

2.xml读

    举个读box中xmin、xmax、ymin、ymax以及类名的例子:

import xml.dom.minidom
dom = xml.dom.minidom.parse( xml_path ) #用于打开一个xml文件,并将这个文件对象dom变量。                                                
root = dom.documentElement #用于得到dom对象的文档元素,并把获得的对象给root
    
name_lst = []
lst_temp = root.getElementsByTagName("name")
for i in range(len(lst_temp)):
    l = lst_temp[i].firstChild.data
    if l in class_name:
       name_lst.append(l)    
                    
xmin_lst1 = root.getElementsByTagName("xmin")
ymin_lst1 = root.getElementsByTagName("ymin")
xmax_lst1 = root.getElementsByTagName("xmax")
ymax_lst1 = root.getElementsByTagName("ymax")
num = min(len(xmin_lst1), len(name_lst))
xmin_lst = []
xmax_lst = []
ymin_lst = []
ymax_lst = []
for i in range(num):
     xmin = int(xmin_lst1[i].firstChild.data)
     xmax = int(xmax_lst1[i].firstChild.data)
     ymin = int(ymin_lst1[i].firstChild.data)
     ymax = int(ymax_lst1[i].firstChild.data)
    
     #print type(xmin_lst1[i].firstChild.data) #
 

3. 写xml
   # 创建dom文档
    doc = Document()
    # 创建根节点
    orderlist = doc.createElement('annotation')
    # 根节点插入dom树
    doc.appendChild(orderlist)
    
    # 每一组信息先创建节点,然后插入到父节点下
    folder = doc.createElement('folder')
    orderlist.appendChild(folder)
    # 创建下的文本节点
    folder_text = doc.createTextNode("VOC2007")
    # 将文本节点插入到下
    folder.appendChild(folder_text)
    
    filename = doc.createElement('filename')
    orderlist.appendChild(filename)
    filename_text = doc.createTextNode(file)
    filename.appendChild(filename_text)
    for i in range(num):
	object = doc.createElement('object')
	orderlist.appendChild(object)
	name = doc.createElement('name')
	object.appendChild(name)
	name_text = doc.createTextNode(name_lst[i])
	name.appendChild(name_text)
		
	pose = doc.createElement('pose')
	object.appendChild(pose)
	pose_text = doc.createTextNode("Unspecified")
	pose.appendChild(pose_text)
				
        #########
	bndbox = doc.createElement('bndbox')
	object.appendChild(bndbox)
	xmin = doc.createElement('xmin')
	bndbox.appendChild(xmin)
	xmin_text = doc.createTextNode(str(xmin_lst[i]))
	xmin.appendChild(xmin_text)
		
	ymin = doc.createElement('ymin')
	bndbox.appendChild(ymin)
	ymin_text = doc.createTextNode(str(ymin_lst[i]))
	ymin.appendChild(ymin_text)
		
	xmax = doc.createElement('xmax')
	bndbox.appendChild(xmax)
	xmax_text = doc.createTextNode(str(xmax_lst[i]))
	xmax.appendChild(xmax_text)
		
	ymax = doc.createElement('ymax')
	bndbox.appendChild(ymax)
	ymax_text = doc.createTextNode(str(ymax_lst[i]))
	ymax.appendChild(ymax_text)
		
with open(save_xml_dir + "/" + file[:len(file)-4] + ".xml", 'w') as f:
    f.write(doc.toprettyxml(indent='\t', encoding='utf-8'))


   



你可能感兴趣的:(other)