我正在尝试使用 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 库,所以我很好奇是否有办法拉出主要项目,同时在遇到任何子项目时不理会?