私の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'
ループの「color」と「weight」属性を繰り返している間、すべての行に見つからないため、weightとcolorはkeyerrorを通過しています。出力をinputxmlと同じにする必要があります:(。このエラーをスキップしてinputxmlと同じにする方法を教えてください。よろしくお願いします。