xml文件解析
发布时间:2020-12-16 23:31:59 所属栏目:百科 来源:网络整理
导读:parse(文件名)打开文件并解析,相比于xml少了打开文件那一步 from xml.etree import ElementTree as ET# 直接解析xml文件tree = ET.parse("xo.xml")# 获取xml文件的根节点root = tree.getroot() 通过getroot获取根节点 ? 对于任何标签都可以有三个特征:标
parse(文件名)打开文件并解析,相比于xml少了打开文件那一步 from xml.etree import ElementTree as ET # 直接解析xml文件 tree = ET.parse("xo.xml") # 获取xml文件的根节点 root = tree.getroot() 通过getroot获取根节点 ? 对于任何标签都可以有三个特征:标签名、标签属性、标签的文本内容(不一定都会把三个写全) import xml.etree.ElementTree as ET # 后面调用都用ETtree = ET.parse("a.xml") # 直接解析xml文件# print(tree) # <xml.etree.ElementTree.ElementTree object at 0x000001BA45A83828>root = tree.getroot() # 获得xml文件的根节点print(root) # <Element ‘data‘ at 0x000001BA45967638>print(list(root))[<Element ‘country‘ at 0x0000021A9FC2CDB8>,<Element ‘country‘ at 0x0000021A9FEDB958>,<Element ‘country‘ at 0x0000021A9FEDBAE8>]对于任何标签都可以有三个特征:标签名、标签属性、标签的文本内容(不一定都会把三个写全)print(root.tag) 标签名print(root.attrib) 标签属性print(root.text) 标签的文本内容print(list(root.iter(‘year‘)))#全文搜索,找到所有[<Element ‘year‘ at 0x0000022042A441D8>,<Element ‘year‘ at 0x0000022042A4BA48>,<Element ‘year‘ at 0x0000022042A4BBD8>]for year in root.iter(‘year‘): print(year.tag) print(year.attrib) year # 没有标签的属性 print(year.text) print(‘=‘*100)print(root.find(‘country‘).attrib) #在root的子节点找,只找一个 # {‘name‘: ‘Liechtenstein‘}print(root.findall(‘country‘).attrib) #在root的子节点找,只找一个 # 错误print([country.attrib for country in root.findall(‘country‘)]) #在root的子节点找,找所有[{‘name‘: ‘Liechtenstein‘},{‘name‘: ‘Singapore‘},{‘name‘: ‘Panama‘}]1、查遍历整个文档for country in root: # 打印整个xml文档 print(‘============>国家 %s‘ %country.attrib) for item in country: print(item.tag) print(item.attrib) print(item.text)2、改for year in root.iter(‘year‘): print(year.tag) year.attrib={‘updated‘:‘yes‘} # 添加year标签属性 year.text=str(int(year.text)+1) # 年份加1 先转换成int进行tree.write(‘a.xml‘)3、增for country in root: rank=country.find(‘rank‘) if int(rank.text) > 50: # print(‘符号条的国家‘,country.attrib) tag=ET.Element(‘egon‘) tag.attrib={‘updated‘:‘yes‘} tag.text=‘NB‘ country.append(tag)#tree.write(‘a.xml‘)4、删for country in root: tag=country.find(‘egon‘) # print(tag,bool(tag)) if tag is not None: print(‘====>‘) country.remove(tag)tree.write(‘a.xml‘) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- SQLite3数据库
- ruby-on-rails-3 – 在任何来源中都找不到rack-1.2.3(Bundl
- waitpid – WIFEXITED返回0虽然孩子正常退出
- Flashback Recovery Area(FRA)相关介绍(一)
- c – 表达式包含未展开的参数包
- 通过AJAX的JS、JQuery两种方式解析XML
- Hybrid--popupwindow--实现下拉菜单spinner--4
- c# – 如何在OWIN CookieAuthenticationProvider中更新声明
- ORACLE-工作常用配置及命令记录-导入sql、unl文件、查看数据
- ruby-on-rails – .seek在ruby中的含义