Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8514167
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T04:47:14+00:00 2026-06-11T04:47:14+00:00

I’m trying to use the pattern described in the event-driven parsing section of the

  • 0

I’m trying to use the pattern described in the “event-driven parsing” section of the lxml tutorial.

In my code I’m calling a function that can recursively run on elements using the iterchildren() method. I’ll just use two nested loop for illustration here.

This works as expected:

xml = StringIO("<root><a><b>data</b><c><d/></c></a><a><z/></a></root>")
for ev, elem in etree.iterparse(xml):
    if elem.tag == 'a':
        for c in elem.iterchildren():
             for gc in c.iterchildren():
                  print gc

The output is <Element d at 0x2df49b0>.

But if I add .clear() in the end:

for ev, elem in etree.iterparse(xml):
    if elem.tag == 'a':
        for c in elem.iterchildren():
             for gc in c.iterchildren():
                  print gc
    elem.clear()

— it doesn’t print anything. Why is it so and what do I do to work around this?

Notes:

  • I can skip iterchildren and do for c in elem or for c in list(elem), with the same effect.
  • I need to use iterative approach to keep the memory usage low.
  • In the real use case, I am doing an element lookup using an attribute:

    if elem.attrib.get('id') == elem_id:
        return _get_info(elem)
    

I would like an explanation of how clear manages to erase the inner elements before they are processed, and how to keep them in memory while they’re needed for processing of the ancestors.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T04:47:16+00:00Added an answer on June 11, 2026 at 4:47 am

    The problem is that iterparse by default yields end events. For subelements end events are generated earlier than for their ancestors:

    >>> for ev, elem in etree.iterparse(xml):
           print elem
    
    <Element b at 0x38fe320>
    <Element d at 0x38fe0f0>
    <Element c at 0x38fe2d0>
    <Element a at 0x38fe190>
    <Element z at 0x38fe230>
    <Element a at 0x38fe3c0>
    <Element root at 0x2df48c0>
    

    In this simple case the problem can be solved by relying on the start events instead:

    for ev, elem in etree.iterparse(xml, events=('start',)):
        ...
    

    However, the linked docs say,

    Note that the text, tail and children of an Element are not
    necessarily there yet when receiving the start event. Only the end
    event guarantees that the Element has been parsed completely.

    That probably means that both start and end events should be processed to allow calling clear() only when it’s safe. I’m thinking of implementing some kind of a stack and pushing things there on start events, popping and clearing on end events.

    I would very much welcome answers that show implementations using this or other ideas.

    Note: the easiest thing to do is just indent the clear call into the if. That would allow accessing grandchildren, but all unrelated elements would remain uncleared.


    EDIT

    I am currently using a state-keeping variable in the following manner:

    found = False
    for event, elem in etree.iterparse(source, events=('start', 'end')):
        if event == 'start':
            if elem.attrib.get('id') == elem_id:
                found = True
        else:
            if elem.attrib.get('id') == elem_id:
                return _get_info(elem)
            if not found:
                elem.clear()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am trying to understand how to use SyndicationItem to display feed which is
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I need a function that will clean a strings' special characters. I do NOT
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I'm trying to create an if statement in PHP that prevents a single post
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.