Home > Blockchain >  XML Parsing text and attrib on same line
XML Parsing text and attrib on same line

Time:10-09

I am working on a school assignment where we have to parse 3 elements from an xml file and print them on the same line with the titles, Artist:, Title:, Decade: in python 3. I was able to complete the Artist and Title part but the decade is a attrib contained in a element that i can only seem to get to print below or I get a "TypeError: 'dict' object is not callable". From my understanding when trying to parse an attrib I must use iter function so i understand why it's wrong but i just can't figure out how to fit that into my for loop so they can all print on the same line. The code is below

This is what I have:

import xml.etree.ElementTree as et

tree = et.parse("cd_catalog.xml")
root = tree.getroot()
for child in root.findall("CD"):
    artist = child.find("ARTIST").text
    title = child.find("TITLE").text
    decade = child.attrib("decade").text
    print("Artist: %s, Title: %s, Decade: %s" %(artist, title, decade))

The XML file has the following info:

<?xml version="1.0" encoding="UTF-8"?>

<CATALOG>


<CD decade="80s">

<TITLE>Empire Burlesque</TITLE>

<ARTIST>Bob Dylan</ARTIST>

<COUNTRY>USA</COUNTRY>

<COMPANY>Columbia</COMPANY>

<PRICE>10.90</PRICE>

<YEAR>1985</YEAR>

</CD>

CodePudding user response:

The attrib attribute of XML elements is not a function but a dictionary of the xml element attributes. Therefore, the expression child.attrib("decade") raises an exception since you try to call child.attrib.

So you have to change:

decade = child.attrib("decade").text

by:

decade = child.attrib["decade"]
  • Related