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

xml模块

时间:2016-11-19 13:04:29      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:new   name   put   root   date   class   pre   生成   rank   

查看

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模块

标签:new   name   put   root   date   class   pre   生成   rank   

原文地址:http://www.cnblogs.com/fengdao/p/6080224.html

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