3

我的 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>

我的python代码:-

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)

得到什么错误:-

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

weight 和 color 正在通过 keyerror,因为在遍历循环时未在所有行中找到“color”和“weight”属性。我需要我的输出应该与输入 xml 相同:(。我怎样才能跳过此错误并使其与输入 xml 相同。提前致谢。

4

1 回答 1

5
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)
于 2012-11-06T04:48:13.360 回答