xml模块
发布日期:2021-08-19 22:02:33 浏览次数:11 分类:技术文章

本文共 1307 字,大约阅读时间需要 4 分钟。

查看

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 ETf = 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")#删除nodefor country in root.findall('country'): #.findall   rank = int(country.find('rank').text)    #.find   if rank > 50:     root.remove(country)       #.removef.write('output.xml')

  

创建xml文档
import xml.etree.ElementTree as ETroot = 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) #打印生成的格式

  

 

转载于:https://www.cnblogs.com/fengdao/p/6080224.html

转载地址:https://blog.csdn.net/weixin_30955341/article/details/98820635 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:P1364 医院设置
下一篇:NYOJ 747 蚂蚁的难题(三)

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年01月04日 12时06分51秒