zoukankan      html  css  js  c++  java
  • xml对标签操作,


    #
    xml是实现不同语言或程序之间交换的协议 # import xml.etree.ElementTree as ET # # tree=ET.parse("fee")#parse是解析fee。xml文件 # root=tree.getroot()#拿到根节点<data></data> # print(root.tag)#输出确认一下 #遍历xml文档 # for i in root: # # print(i.tag)#打印出<data></data>下标签名字《contry》 # # print(i.attrib)#打印变迁的属性值即name='dsf' # for j in i:#找下一级的标签名 # # print(j.tag) # #print(j.attrib)#子标签的属性值{'updated': 'yes'} 源代码<rank updated="yes">2</rank> # print(j.text)#找到标签内容 # for child in root: # print(child.tag,child.attrib) # for i in child: # print(i.tag,i.text) # #只遍历year节点 # for node in root.iter('year'):#从根country拿year拿的是所有的year标签以node为名 # print(node.tag,node.text)#标签名以及内容 import xml.etree.ElementTree as ET#重点 res=ET.Element("namelist")#创建《name》《/name》 age=ET.SubElement(res,'name',attrib={'color':'red'}) # <namelist> # <name color='red'></name> # </namelist> et=ET.ElementTree(res)#生成文档对象,背下来 et.write('abc.xml',encoding='utf8',xml_declaration=True)#写入,declaration表示xml声明 tree=ET.parse("fee.xml")#parse是解析fee。xml文件tree相当于是f root=tree.getroot()#拿到根节点<data></data> # #修改 # for node in root.iter('year'):#拿到year标签 # newyear=int(node.text)+1#内容值+1变成2009 # node.text=str(newyear)#转换成字符串赋给节点 # node.set('updated','no')#为标签设置属性updated=’no‘ # tree.write('fee')#昨晚需要的操作之后需要写入文件,tree是前面写的相当于是文件操作的f #删除 # for node in root.iter('contry'):#重点是root.iter("")这个函数的使用 # rank=int(node.find('rank').text)#node.find("")学会使用find函数获取rank标签的文本内容 # if rank>5: # root.remove(node) # tree.write("fee")#如果写fee.xml那么就是新建一个fee.xml.xml的文件,是新建文件写入,所以不要加xml
    新建new,选择file,然后选择xml
    <data> <contry name="lihai"> <rank updated="yes">2</rank> <year updated="no">2009</year> <gdppc>4561</gdppc> <neighbour direction="e" name="sfa" /> <neighbour direction="g" name="tghh" /> </contry> </data>
    
    
    
     
  • 相关阅读:
    237. Delete Node in a Linked List
    430. Flatten a Multilevel Doubly Linked List
    707. Design Linked List
    83. Remove Duplicates from Sorted List
    160. Intersection of Two Linked Lists
    426. Convert Binary Search Tree to Sorted Doubly Linked List
    142. Linked List Cycle II
    类之间的关系
    初始化块
    明确类和对象
  • 原文地址:https://www.cnblogs.com/wfl9310/p/9026633.html
Copyright © 2011-2022 走看看