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

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

在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']


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5646232.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存