通过KeyE迭代python中的xml

2024-10-08 18:21:45 发布

您现在位置: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代码:-

^{pr2}$

我得到的错误是:

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

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


Tags: namepy错误greenxmlbookscolorweight
1条回答
网友
1楼 · 发布于 2024-10-08 18:21:45
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)

相关问题 更多 >

    热门问题