我的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'
重量和颜色是通过keyerror,因为迭代循环“颜色”和“重量”属性没有在所有行中找到。我需要我的输出应该与输入xml相同:(。 如何跳过此错误并使其与输入xml相同。提前谢谢。
答案 0 :(得分:3)
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)