该代码将监视’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']