【发布时间】:2014-11-20 03:34:52
【问题描述】:
我有一些看起来像这样的 xml:
<topic>
<restrictions>
<restriction id="US"/>
<restriction id="CA"/>
<restriction id="EU"/>
</restrictions>
</topic>
<topic>
<restrictions>
<restriction id="JP"/>
<restriction id="AU"/>
<restriction id="EU"/>
<restriction id="US"/>
</restrictions>
</topic>
以及具有相同模式的不同迭代。我已经在我的脚本中使用 minidom 来用 xml 做一些其他的事情。对于上面的示例,我需要得到以下结果:
[['US','CA','EU'],['JP','AU','EU','US']]
我尝试了不同的迭代,但结果不正确。这是我的代码:
from xml.dom import minidom
xmldoc = minidom.parse(path_to_file)
itemlist = xmldoc.getElementsByTagName('restrictions')
itemlist2 = xmldoc.getElementsByTagName('restriction')
restrictions=[]
for x in itemlist:
res=[]
for s in itemlist2:
res.append(s.attributes['id'].value)
restrictions.append(res)
print(restrictions)
您能帮我正确进行迭代吗?任何帮助表示赞赏。谢谢!
编辑:刚刚意识到可能会发生其他事情,我需要考虑以防万一。也可能会发生主题元素根本没有元素的情况,当这种情况发生时,附加到列表中的值应该只是 0。有什么简单的方法可以产生这种情况?
【问题讨论】:
标签: python python-3.x minidom