Sreeni Puthiyillam
Sreeni Puthiyillam

Reputation: 485

Iterating through xml in python through KeyError

My Xml :

<books>
<book name="goodbook" cost="10" color="green"></book>
<book name="badbook" cost="1000" weight="100"></book>
<book name="avgbook" cost="99" weight="120"></book>
</books>

My python code :-

import xml.etree.ElementTree as ET
import sys
doc       = ET.parse("books.xml")
root      = doc.getroot() 
root_new  = ET.Element("books") 
for child in root:
       name                = child.attrib['name']
       cost                = child.attrib['cost']
       color               = child.attrib['color'] #KeyError
       weight              = child.attrib['weight'] #KeyError
       # create "book" here
       book    = ET.SubElement(root_new, "book") 
       book.set("name",name)               
       book.set("cost",cost) 
       book.set("color",color) 
       book.set("weight",weight)
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)

What error am getting :-

python books.py 
Traceback (most recent call last):
  File "books.py", line 10, in <module>
    weight              = child.attrib['weight'] #KeyError
KeyError: 'weight'

weight and color are throughing keyerror, because while iterating through loop "color" and "weight" attribute not found in all line. i need my out put should be same as input xml :( . How can i skip this error and make it same as input xml . Thanks in advance.

Upvotes: 4

Views: 5827

Answers (1)

light
light

Reputation: 421

for child in root:
    name                = child.attrib['name']
    cost                = child.attrib['cost']
    # create "book" here
    book    = ET.SubElement(root_new, "book") 
    book.set("name",name)               
    book.set("cost",cost) 
    if 'color' in child.attrib:
        color               = child.attrib['color']
        book.set("color",color) 
    if 'weight' in child.attrib:
        weight              = child.attrib['weight']
        book.set("weight",weight)

Upvotes: 8

Related Questions