首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用minidom迭代属性值

用minidom迭代属性值
EN

Stack Overflow用户
提问于 2014-11-20 03:34:52
回答 1查看 1.3K关注 0票数 1

我有一些类似于以下内容的xml:

代码语言:javascript
复制
<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做一些其他事情。对于上面的示例,我需要得到以下结果:

代码语言:javascript
复制
[['US','CA','EU'],['JP','AU','EU','US']]

我用不正确的结果尝试了不同的迭代。这是我的密码:

代码语言:javascript
复制
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。什么是制造这种情况的简单方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-20 04:17:27

getElementsByTagName返回具有相应标记名的所有元素。因此,itemlist2包含restriction中的所有restriction注释。在您的代码中,它将为每个['US','CA','EU','JP','AU','EU','US']节点添加所有这些节点restrictions。因此,您应该尝试在循环中分别为每个restriction节点获取restrictions节点。

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27031269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档