使用Python lxml和Iterparse解析大型XML文件
我正在尝试使用lxml库和iterparse方法来解析一个非常大的xml文件,这个文件里包含了很多项目。
我的文件格式是:
<item>
<title>Item 1</title>
<desc>Description 1</desc>
<url>
<item>http://www.url1.com</item>
</url>
</item>
<item>
<title>Item 2</title>
<desc>Description 2</desc>
<url>
<item>http://www.url2.com</item>
</url>
</item>
到目前为止,我的解决方案是:
from lxml import etree
context = etree.iterparse( MYFILE, tag='item' )
for event, elem in context :
print elem.xpath( 'description/text( )' )
elem.clear( )
while elem.getprevious( ) is not None :
del elem.getparent( )[0]
del context
当我运行它时,我得到的结果类似于:
[]
['description1']
[]
['description2']
那些空的集合是因为它还提取了url标签下的子项标签,而这些标签显然没有描述字段可以用xpath提取。我希望能逐个解析出每个项目,然后根据需要处理子字段。我现在正在学习lxml库,所以我想知道有没有办法在遇到子项目时只提取主要项目,而不去碰那些子项目呢?
1 个回答
4
其实整个xml文件都是由核心部分来解析的。etree.iterparse就像是一个生成器的视图,它可以根据标签名简单过滤数据(具体可以查看文档 http://lxml.de/api/lxml.etree.iterparse-class.html)。
如果你想要更复杂的过滤,那就得自己来实现了。
一种解决方案是:同时注册开始事件:
iterparse(self, source, events=("start", "end",), tag="item")
并且需要一个布尔值来判断你是否在“item”结束时,也就是在“item/url/item”结束时。