这是我访问 XML 文件的 python 代码:
import xml.etree.ElementTree as ET
def display_book(book):
root = ET.parse(source="library.xml")
info = root.iter("catalog")
for elem in info:
name = elem.find("book").attrib['id']
if name == book:
print(name)
return "Book Not Found"
#Main
display_book("bk105")
以下是 XML 代码示例:
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>
An in-depth look at creating applications with XML.
</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>
A former architect battles corporate zombies, an evil sorceress,
and her own childhood to become queen of the world.
</description>
</book>
</catalog>
书籍从“bk101”到“bk112”,代码仅查找“bk101”的 id 作为第一本书,而不是迭代每本书 id 并与输入交叉引用它,因此程序永远不会输出任何事物。甚至没有“找不到书”。
最佳答案
elem.find("book")
仅返回目录中的第一本书。您需要使用elem.findall("book")
,然后迭代它们。
但是您可以使用 root.iter("book")
直接迭代书籍。
for elem in root.iter("book"):
name = elem.attrib('id')
if name == book:
print(name)
else:
print("Book not found")
您还应该将错误消息放入 else:
block 中。否则即使找到书也会被退回。
关于python - 我的 Python 无法正确读取 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56943916/