【问题标题】:Iterate through attribute values with minidom使用 minidom 遍历属性值
【发布时间】: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


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 您的回答很完美,效果也很好,但是您能快速浏览一下我对这个问题的编辑吗?谢谢!!
    • @rodrigocf 你的意思是如果一个主题没有限制节点,应该在结果列表中插入0?
    • 没错,例如,如果我们在上面的示例中添加第三个没有&lt;restrictions&gt; 的主题,结果应该是[['US','CA','EU'],['JP','AU','EU','US'],0]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2014-10-25
    • 1970-01-01
    • 2013-07-05
    • 2012-10-29
    • 2016-08-11
    相关资源
    最近更新 更多