4

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.

0

1 Answer 1

8
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)
Sign up to request clarification or add additional context in comments.

1 Comment

Wow "light" you are really a light in program, super dude its working..With in 7 minutes i accept this answer. Thanks for your time:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.