python - 通过KeyError遍历python中的xml

标签 python

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

相关文章:

python - 如何将此代码从 matlab 转换为 python?

python - 如何使用 pathlib 从当前路径的一部分创建一个新的 Path 对象?

python - Windows 中的 Poetry 安装不起作用

python - OpenSSH 公钥不适用于 Cygwin

python - 为 C++ 项目创建 Python 绑定(bind)的常用技术是什么?

python - 用于在文件中查找有效单词的正则表达式

python - OpenCV/Python Bundle调整

Python从配置创建字典的字典

python - Pylons 中的信号处理

python - 根据日期条件删除行