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

  • Home
  • SEARCH
  • 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 3680426
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T03:34:31+00:00 2026-05-19T03:34:31+00:00

I have a xml like this: <a> <b>hello</b> <b>world</b> </a> <x> <y></y> </x> <a>

  • 0

I have a xml like this:

<a>
    <b>hello</b>
    <b>world</b>
</a>
<x>
    <y></y>
</x>
<a>
    <b>first</b>
    <b>second</b>
    <b>third</b>
</a>

I need to iterate through all <a> and <b> tags, but I don’t know how many of them are in document. So I use xpath to handle that:

from lxml import etree

doc = etree.fromstring(xml)

atags = doc.xpath('//a')
for a in atags:
    btags = a.xpath('b')
    for b in btags:
            print b

It works, but I have pretty big files, and cProfile shows me that xpath is very expensive to use.

I wonder, maybe there is there more efficient way to iterate through indefinitely number of xml-elements?

  • 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-05-19T03:34:32+00:00Added an answer on May 19, 2026 at 3:34 am

    XPath should be fast. You can reduce the number of XPath calls to one:

    doc = etree.fromstring(xml)
    btags = doc.xpath('//a/b')
    for b in btags:
        print b.text
    

    If that is not fast enough, you could try Liza Daly’s fast_iter. This has the advantage of not requiring that the entire XML be processed with etree.fromstring first, and parent nodes are thrown away after the children have been visited. Both of these things help reduce the memory requirements. Below is a modified version of fast_iter which is more aggressive about removing other elements that are no longer needed.

    def fast_iter(context, func, *args, **kwargs):
        """
        fast_iter is useful if you need to free memory while iterating through a
        very large XML file.
    
        http://lxml.de/parsing.html#modifying-the-tree
        Based on Liza Daly's fast_iter
        http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
        See also http://effbot.org/zone/element-iterparse.htm
        """
        for event, elem in context:
            func(elem, *args, **kwargs)
            # It's safe to call clear() here because no descendants will be
            # accessed
            elem.clear()
            # Also eliminate now-empty references from the root node to elem
            for ancestor in elem.xpath('ancestor-or-self::*'):
                while ancestor.getprevious() is not None:
                    del ancestor.getparent()[0]
        del context
    
    def process_element(elt):
        print(elt.text)
    
    context=etree.iterparse(io.BytesIO(xml), events=('end',), tag='b')
    fast_iter(context, process_element)
    

    Liza Daly’s article on parsing large XML files may prove useful reading to you too. According to the article, lxml with fast_iter can be faster than cElementTree‘s iterparse. (See Table 1).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

If I have some xml like this: <mynode> <mysubnode> <mysubsubnode>hello world</mysubsubnode> some more text
I have an XML document with some sample content like this: <someTag> <![CDATA[Hello World]]>
If I have an XML document like this: <root> <elem name=Greeting> Hello </elem> <elem
Let's say I have some XML like this <channel> <item> <title>This is title 1</title>
Greetings! I have some XML like this: <Root> <AlphaSection> . . . </AlphaSection> <BetaSection>
Greetings! I have some XML like this: <Root> <MainSection> <SomeNode>Some Node Value</SomeNode> <SomeOtherNode>Some Other
I have an xml file like this: <root> <item> <name>one</name> <status>good</status> </item> <item> <name>two</name>
So I have xml that looks like this: <todo-list> <id type=integer>#{id}</id> <name>#{name}</name> <description>#{description}</description> <project-id
I have normally hand written xml like this: <tag><?= $value ?></tag> Having found tools
I have an xml that looks like this: <Config> <A></A> <Template><B/><C/></Template> </Config> and I

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.