我的 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 是 throughing keyerror,因为在遍历循环时找不到所有行中的“color”和“weight”属性。我需要我的输出应该与输入 xml 相同:(。 我怎样才能跳过这个错误并使其与输入 xml 相同。提前致谢。
最佳答案
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)
关于python - 通过KeyError遍历python中的xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244533/