[英]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”的报价? 有没有一种方法不能全部加载? 那我如何获得作者和文本的价值呢?
您必须自己构建该数据结构。 在这种情况下,我选择了一个嵌套字典:
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'}}
然后,您可以直接访问所需的每个“日”,例如output[0]
, output[1]
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.