我想在python中使用ElementTree处理以下xml。 当UserValue标题为THIRD并且其值不为空时,我需要找到所有实例名称。所以在这个例子中,结果将是大理石和鼠标。
<?xml version="1.0" encoding="utf-8"?>
<Data>
<Instance id="61" name="atom">
<UserData id="30">
<UserValue value="" title="FIRST"></UserValue>
<UserValue value="" title="SECOND"></UserValue>
<UserValue value="" title="THIRD"></UserValue>
<UserValue value="watch" title="FOURTH"></UserValue>
</UserData>
</Instance>
<Instance id="64" name="marble" ref="33">
<UserData id="34">
<UserValue value="" title="FIRST"></UserValue>
<UserValue value="stuff" title="SECOND"></UserValue>
<UserValue value="airplane" title="THIRD"></UserValue>
<UserValue value="" title="FOURTH"></UserValue>
</UserData>
</Instance>
<Instance id="65" name="rock">
<UserData id="36">
<UserValue value="" title="FIRST"></UserValue>
<UserValue value="" title="SECOND"></UserValue>
<UserValue value="" title="THIRD"></UserValue>
<UserValue value="" title="FOURTH"></UserValue>
</UserData>
</Instance>
<Instance id="66" name="mouse">
<UserData id="38">
<UserValue value="" title="FIRST"></UserValue>
<UserValue value="" title="SECOND"></UserValue>
<UserValue value="rocket" title="THIRD"></UserValue>
<UserValue value="" title="FOURTH"></UserValue>
</UserData>
</Instance>
</Data>
这是我想出的python代码。它工作正常,返回大理石和鼠标。 有没有办法使用findall或finditer来做同样的事情?
另外一个问题是,ElementTree似乎将整个xml加载到内存中进行处理,这可能是我的真实xml的问题,接近300MB。
import xml.etree.ElementTree as xml
tree = xml.parse("example.xml")
for node in tree.iter('Instance'):
name = node.get('name')
for col in node.iter('UserValue'):
title = col.attrib.get('title')
value = col.attrib.get('value')
if (title == "THIRD" and value != ""):
print " name =", name
答案 0 :(得分:2)
我建议您使用lxml。您可以将xpath表达式与lxml一起使用。
import lxml.etree
root = lxml.etree.parse("example.xml")
for instance in root.xpath('//Instance[descendant::UserValue[@title = "THIRD"][@value != ""]]'):
print instance.get('name')
如果上面的代码占用太多内存,请尝试以下代码:
import lxml.etree
class InstanceNamePrinter(object):
def start(self, tag, attrib):
if tag == 'Instance':
self.name = attrib['name']
elif tag == 'UserValue':
if attrib['title'] == 'THIRD' and attrib['value'] != '':
print self.name
def close(self):
pass
with open('example.xml') as xml:
parser = lxml.etree.XMLParser(target=InstanceNamePrinter())
lxml.etree.parse(xml, parser)