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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T15:03:49+00:00 2026-06-09T15:03:49+00:00

I’m using Python with ElementTree to parse an XML file. I want to be

  • 0

I’m using Python with ElementTree to parse an XML file. I want to be able to make a list of dictionaries containing the information of all the CDs. I can use this list later to gather information, like displaying the title of CDs coming from the USA. The code below is working, but can easily be broken if the YEAR tag is not the last tag of CD. How can I rewrite this code so that tags could be in any order?

from xml.etree.ElementTree import ElementTree

f = open("cd_catalog.xml")
tree = ElementTree()
tree.parse(f)

catalog = []
cd = {}
for node in tree.iter():
    if node.tag != "CD" and node.tag != "CATALOG":
        tagtext = (node.tag,node.text),
        cd.update(tagtext)
    if node.tag == "YEAR":
        catalog.append(cd)
        cd = {}

for cd in catalog:
    if cd["COUNTRY"] == "USA":
        print("The cd named {0} is from USA".format(cd["TITLE"]))

2 entries of the xml file :

<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>
  • 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-09T15:03:50+00:00Added an answer on June 9, 2026 at 3:03 pm

    One way to rewrite your XML parsing code is the following. In this this I define a generator which loops over all the CD elements of the root element (I do not check that this is a CATALOG element, although you could add that check in). This generator returns all of the sub-elements of each CD element as a dictionary.

    The use of a generator is more efficient than building a dictionary of all the CD elements, particularly if your XML file is very large, since you only ever store a single CD element in memory.

    import xml.etree.ElementTree as etree
    
    def get_cd(element):
        try:
            for el in element.iter(tag='CD')
                yield get_cd_info(el)
        except AttributeError:
            # Python < 2.7
            for el in element.getiterator(tag='CD')
                yield get_cd_info(el)
    
    def get_cd_info(element):
        return {'title':element.findtext('TITLE'),
            'artist':element.findtext('ARTIST'),
            'country':element.findtext('COUNTRY'),
            'company':element.findtext('COMPANY'),
            'price':element.findtext('PRICE),
            'year':element.findtext('YEAR')}
    

    Here is the above method in action:

    s = '''<CATALOG>
        <CD>
            <TITLE>Empire Burlesque</TITLE>
            <ARTIST>Bob Dylan</ARTIST>
            <COUNTRY>USA</COUNTRY>
            <COMPANY>Columbia</COMPANY>
            <PRICE>10.90</PRICE>
            <YEAR>1985</YEAR>
        </CD>
        <CD>
            <TITLE>Hide your heart</TITLE>
            <ARTIST>Bonnie Tyler</ARTIST>
            <COUNTRY>UK</COUNTRY>
            <COMPANY>CBS Records</COMPANY>
            <PRICE>9.90</PRICE>
            <YEAR>1988</YEAR>
        </CD>
    </CATALOG>
    '''
    
    e = etree.fromstring(s)
    
    for cd in get_cd(e):
        if cd['country'] == 'USA':
            print('The cd "{0}" is from the USA.'.format(cd['title']))
    
    # prints 'The cd "Empire Burlesque" is from the USA.'
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We are using XSLT to translate a RIXML file to XML. Our RIXML contains
i want to parse a xhtml file and display in UITableView. what is the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I want use html5's new tag to play a wav file (currently only supported
I have a French site that I want to parse, but am running into
In my XML file chapters tag has more chapter tag.i need to display chapters
I'm parsing an XML file, the creators of it stuck in a bunch social
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
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.