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 81287
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T21:26:11+00:00 2026-05-10T21:26:11+00:00

I am currently running the following code based on Chapter 12.5 of the Python

  • 0

I am currently running the following code based on Chapter 12.5 of the Python Cookbook:

from xml.parsers import expat  class Element(object):     def __init__(self, name, attributes):         self.name = name         self.attributes = attributes         self.cdata = ''         self.children = []     def addChild(self, element):         self.children.append(element)     def getAttribute(self,key):         return self.attributes.get(key)     def getData(self):         return self.cdata     def getElements(self, name=''):         if name:             return [c for c in self.children if c.name == name]         else:             return list(self.children)  class Xml2Obj(object):     def __init__(self):         self.root = None         self.nodeStack = []     def StartElement(self, name, attributes):         element = Element(name.encode(), attributes)         if self.nodeStack:             parent = self.nodeStack[-1]             parent.addChild(element)         else:             self.root = element         self.nodeStack.append(element)     def EndElement(self, name):         self.nodeStack.pop()     def CharacterData(self,data):         if data.strip():             data = data.encode()             element = self.nodeStack[-1]             element.cdata += data     def Parse(self, filename):         Parser = expat.ParserCreate()         Parser.StartElementHandler = self.StartElement         Parser.EndElementHandler = self.EndElement         Parser.CharacterDataHandler = self.CharacterData         ParserStatus = Parser.Parse(open(filename).read(),1)         return self.root 

I am working with XML documents of about 1 GB in size. Does anyone know a faster way to parse these?

  • 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. 2026-05-10T21:26:11+00:00Added an answer on May 10, 2026 at 9:26 pm

    I looks to me as if you do not need any DOM capabilities from your program. I would second the use of the (c)ElementTree library. If you use the iterparse function of the cElementTree module, you can work your way through the xml and deal with the events as they occur.

    Note however, Fredriks advice on using cElementTree iterparse function:

    to parse large files, you can get rid of elements as soon as you’ve processed them:

    for event, elem in iterparse(source):     if elem.tag == "record":         ... process record elements ...         elem.clear() 

    The above pattern has one drawback; it does not clear the root element, so you will end up with a single element with lots of empty child elements. If your files are huge, rather than just large, this might be a problem. To work around this, you need to get your hands on the root element. The easiest way to do this is to enable start events, and save a reference to the first element in a variable:

    # get an iterable context = iterparse(source, events=("start", "end"))  # turn it into an iterator context = iter(context)  # get the root element event, root = context.next()  for event, elem in context:     if event == "end" and elem.tag == "record":         ... process record elements ...         root.clear() 

    The lxml.iterparse() does not allow this.

    The previous does not work on Python 3.7, consider the following way to get the first element.

    import xml.etree.ElementTree as ET  # Get an iterable. context = ET.iterparse(source, events=("start", "end"))      for index, (event, elem) in enumerate(context):     # Get the root element.     if index == 0:         root = elem     if event == "end" and elem.tag == "record":         # ... process record elements ...         root.clear() 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 194k
  • Answers 194k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The best solution may be to use an adapter pattern.… May 12, 2026 at 6:42 pm
  • Editorial Team
    Editorial Team added an answer Seems as though this was due to a weird issue… May 12, 2026 at 6:42 pm
  • Editorial Team
    Editorial Team added an answer Use error_message_on instead of error_messages to get the message for… May 12, 2026 at 6:42 pm

Related Questions

I am trying to do positioning in JavaScript. I am using a cumulative position
I am currently developing in 3.5 (building to 3.5 as I am using LINQ)
I am receiving an error a web based application that allows corporate intranet users
I have a .jsp that contains an IFrame with a page that has some

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.