栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在python中解析具有多个根元素的xml文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在python中解析具有多个根元素的xml文件

如果需要,此代码将填充一种方法的详细信息。

该代码将监视’accumulated_xml,直到遇到另一个xml文档的开头或文件的结尾。当它具有完整的xml文档时,它会调用

display
以行使该
lxml
库来解析该文档并报告一些内容。

>>> from lxml import etree>>> def display(alist):...     tree = etree.fromstring(''.join(alist))...     for country in tree.xpath('.//country'):...         print(country.attrib['name'], country.find('rank').text, country.find('year').text)...         print([neighbour.attrib['name'] for neighbour in country.xpath('neighbor')])... >>> accumulated_xml = []>>> with open('temp.xml') as temp:...     while True:...         line = temp.readline()...         if line:...  if line.startswith('<?xml'):...      if accumulated_xml:...          display (accumulated_xml)...          accumulated_xml = []...  else:...      accumulated_xml.append(line.strip())...         else:...  display (accumulated_xml)...  break... Liechtenstein 1 2008['Austria', 'Switzerland']Singapore 4 2011['Malaysia']Panama 68 2011['Costa Rica', 'Colombia']Liechtenstein1 1 2008['Austria1', 'Switzerland1']Singapore 4 2011['Malaysia1']Panama 68 2011['Costa Rica', 'Colombia']


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640428.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号