2

我想在 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 加载到内存中进行处理,这对于我接近 300MB 的真实 xml 来说可能是个问题。

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
4

1 回答 1

3

我建议您使用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)
于 2013-07-12T16:14:34.947 回答