我有一些类似于以下内容的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)你能帮我正确地得到迭代吗?任何帮助都是非常感谢的。谢谢!
编辑:只是意识到其他事情可能会发生,我需要说明以防万一。还可能发生这样的情况: topic元素根本没有元素,当发生这种情况时,添加到列表中的值应该仅为0。什么是制造这种情况的简单方法?
发布于 2014-11-20 04:17:27
getElementsByTagName返回具有相应标记名的所有元素。因此,itemlist2包含restriction中的所有restriction注释。在您的代码中,它将为每个['US','CA','EU','JP','AU','EU','US']节点添加所有这些节点restrictions。因此,您应该尝试在循环中分别为每个restriction节点获取restrictions节点。
from xml.dom import minidom
xmldoc = minidom.parse(path_to_file)
restrictions=[]
topic_nodes = xmldoc.getElementsByTagName('topic')
for topic_node in topic_nodes:
restrictions_nodes = topic_node.getElementsByTagName('restrictions')
if not restrictions_nodes:
restrictions.append(0)
continue
result = []
for restrictions_node in restrictions_nodes:
restriction_nodes = restrictions_node.getElementsByTagName('restriction')
for restriction_node in restriction_nodes:
result.append(restriction_node.attributes['id'].value)
restrictions.append(result)
print(restrictions)https://stackoverflow.com/questions/27031269
复制相似问题