Python 按键值读取 xml 列表

Python read xml list by key-value

我正在尝试通过 Python 阅读报价单。该列表如下所示:

<quotelist
    xmlns="http://www.w3schools.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="quotationlist.xsd">
    <quote key = "0">
        <author>Author 0</author>
        <text>Text 0</text>
    </quote>
    <quote key = "1">
        <author>Author 1</author>
        <text>Text 1.</text>
    </quote>
    <quote key = "2">
        <author>Author 2</author>
        <text>Text 2.</text>
    </quote>
</quotelist>

我想将其作为一天一次引用,因此关键是一年中的第几天(0 到 364)。 但是我很难用 Python.

读出第 x 天
from xml.dom import minidom
dayOfYear = 44 #not relevant, I know how to find this out
mydoc = minidom.parse('./media/quotes.xml')
items = mydoc.getElementsByTagName('quote')
print(items)

这给了我格式为 的 365 个引号列表,这就是我例外的地方。但是有没有找到键号为 "dayOfYear" 的报价的功能?有没有办法不全部加载?那么如何获取 author 和 text 的值呢?

您必须自己构建该数据结构。在这种情况下,我选择了一个嵌套的字典:

items = mydoc.getElementsByTagName('quote')
output = {int(item.getAttribute('key')): {'author': item.getElementsByTagName('author')[0].firstChild.nodeValue,
                                          'text': item.getElementsByTagName('text')[0].firstChild.nodeValue}
          for item in items}

print(output)

产出

{0: {'author': 'Author 0',
     'text': 'Text 0'},
 1: {'author': 'Author 1',
     'text': 'Text 1'},
 2: {'author': 'Author 2',
     'text': 'Text 2'}}

然后您可以直接访问您想要的每个"day",例如output[0]output[1]