当使用ElementTree的iterparse方法时,如何知道元素的父元素?

时间:2012-02-17 16:39:47

标签: python xml parsing celementtree

我想循环遍历xml文件的元素并产生每个元素,除非父元素是一个特征。

所以在伪代码中

    for event, element in cElementTree.iterparse('../test.xml'):
        if parentOf_element != 'feature':
        yield element

如何获取元素的父元素?我知道有可能使用tree.getiterator()函数,但我不想构建完整的树,因为xml文件很大。

2 个答案:

答案 0 :(得分:2)

您可以使用lxml执行此操作。它有getparent()。

或者,可以处理startend个事件,并使用feature跳过cElementTree个孩子:

from xml.etree import cElementTree as etree

in_feature_tag = False
for event, element in etree.iterparse('test.xml', events=('start', 'end')):
    if element.tag == 'feauture':
        in_feature_tag = event == 'start'
    if event == 'end' and not in_feature_tag:
        yield element

答案 1 :(得分:1)

如果启用start事件,则可以使用堆栈跟踪祖先节点。如果你真的想要压制<feature>的所有后代,而不仅仅是孩子,你可以使用一个简单的标志,如另一个答案所示。

您可以使用root.clear()吹走所有已完成的元素。阅读this

代码:

import xml.etree.cElementTree as et
# Produces identical answers with import lxml.etree as et
import cStringIO

def normtext(t):
    return repr("" if t is None else t.strip())

def dump(el):
    print el.tag, normtext(el.text), normtext(el.tail), el.attrib

def my_filtered_elements(source, skip_parent_tag="feature"):
    # get an iterable
    context = et.iterparse(source, events=("start", "end"))
    # turn it into an iterator
    context = iter(context)
    # get the root element
    event, root = context.next()
    tag_stack = [None, root.tag]
    for event, elem in context:
        # print event, elem.tag, tag_stack
        if event == "start":
            tag_stack.append(elem.tag)
        else:
            assert event == "end"
            my_tag = tag_stack.pop()
            assert my_tag == elem.tag
            parent_tag = tag_stack[-1]
            if parent_tag is not None and parent_tag != skip_parent_tag:
                dump(elem)
                # yield elem
            root.clear()

def other_filtered_elements(source, skip_parent_tag="feature"):            
    in_feature_tag = False
    for event, element in et.iterparse(source, events=('start', 'end')):
        if element.tag == skip_parent_tag:
            in_feature_tag = event == 'start'
        if event == 'end' and not in_feature_tag:
            dump(element)            

test_input = """
<top>
    <lev1 guff="1111">
        <lev2>aaaaa</lev2>
        <lev2>bbbbb</lev2>
    </lev1>
    <feature>
        feat text 1
        <fchild>fcfcfcfc
            <fgchild>ggggg</fgchild>    
        </fchild>
        feat text 2
    </feature>
    <lev1 guff="2222">
        <lev2>ccccc</lev2>c-tail
        <lev2>ddddd</lev2>d-tail
        <notext1></notext1>e-tail
        <notext2 />f-tail
     </lev1>g-tail
</top>
"""

print "=== me ==="
my_filtered_elements(cStringIO.StringIO(test_input))
print "=== other ==="
other_filtered_elements(cStringIO.StringIO(test_input))

输出如下。您会从lev1节点注意到root.clear()没有吹走尚未完全解析的元素。这意味着使用的内存量是O(树的深度),而不是O(树中元素的总数)

=== me ===
lev2 'aaaaa' '' {}
lev2 'bbbbb' '' {}
lev1 '' '' {'guff': '1111'}
fgchild 'ggggg' '' {}          <<<=== do you want this?
feature 'feat text 1' '' {}
lev2 'ccccc' 'c-tail' {}
lev2 'ddddd' 'd-tail' {}
notext1 '' 'e-tail' {}
notext2 '' 'f-tail' {}
lev1 '' 'g-tail' {'guff': '2222'}
=== other ===
lev2 'aaaaa' '' {}
lev2 'bbbbb' '' {}
lev1 '' '' {'guff': '1111'}
feature 'feat text 1' '' {}
lev2 'ccccc' 'c-tail' {}
lev2 'ddddd' 'd-tail' {}
notext1 '' 'e-tail' {}
notext2 '' 'f-tail' {}
lev1 '' 'g-tail' {'guff': '2222'}
top '' '' {}                           <<<=== do you want this?