首页 > 代码库 > xml模块

xml模块

查看

f = ET.parse(‘xmltest‘)     #解析
root = f.getroot()  #root为根节点
print(root.tag)         #tag 标签

#遍历xml文档
for child in root:
    print(child.tag,child.attrib)   #.attrib归属,属性
    for i in child:
        print(‘\t‘,i.tag,i.attrib,i.text)


#只遍历year 节点
for node in root.iter(‘year‘):      #.iter  方法
    print(node.tag,node.text)       #.text  .tag

  

修改和删除xml文档内容

import xml.etree.ElementTree as ET
f = ET.parse(‘xmltest‘)
root = f.getroot()

#修改
for node in root.iter(‘year‘):      #.iter
    new_year = int(node.text)+1
    node.text = str(new_year)       #.text
    node.set("updated","yes")       #.set   增加属性

f.write("xmltest2")


#删除node
for country in root.findall(‘country‘): #.findall
   rank = int(country.find(‘rank‘).text)    #.find
   if rank > 50:
     root.remove(country)       #.remove

f.write(‘output.xml‘)

  

创建xml文档

import xml.etree.ElementTree as ET

root = ET.Element("namelist")

name = ET.SubElement(root,‘name‘,attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,‘sex‘)
sex.text = ‘33‘

name2 = ET.SubElement(root,‘name2‘,attrib={"enrolled":"no"})
age = ET.SubElement(name,"age")
age.text = ‘19‘

et = ET.ElementTree(root) #生成文档对象
et.write("xmltest3.xml", encoding="utf-8",xml_declaration=True)

ET.dump(root) #打印生成的格式

  

 

xml模块