【问题标题】:python minidom - get data from parent nodes with the same namepython minidom - 从同名的父节点获取数据
【发布时间】:2015-03-11 06:40:29
【问题描述】:

我有一个这样结构的xml文件:

<zone id=1 name=one>
  <subzone>
    <zone id=2 name=subone>
      ...
        <item>
        <item>
        ...

<zone id=1 name=two>
  <subzone>
    <zone id=2 name=subtwo>
      ...
        <item>
        <item>
        ...

我想获取所有项目的列表,其中包含有关其父母的信息。例如 - item, zone_id=1, zone_name=two, subzone_id=2, subzone_name=subtwozone 节点的数量对于 items 组是不同的。 我可以得到所有区域的列表:

def read_region(self, xml):
    doc = minidom.parse(xml)
    node = doc.getElementsByTagName("zone")
    for zone in node:
        print(zone.getAttribute("name"))

如果有很多具有相同节点名的节点,我如何从特定节点获取数据?或者是否有可能得到一个元素的所有父节点的信息?

【问题讨论】:

    标签: python xml parsing dom minidom


    【解决方案1】:

    你问了两个问题:

    1. 如何从多个同名元素中获取特定元素?
    2. 如何获取给定元素的所有父元素?

      1. 要获取特定元素,您必须确定该元素的什么不同。它可能是与唯一可识别的另一个元素的关系。

      2. 你可以通过重复调用node.getparent()来获取一个元素的所有父元素,如下所示。见http://lxml.de/api/lxml.etree._Element-class.html

        def get_parents(element):
            ancestors = []
            parent = element.getparent()
            while parent != None:
                ancestors.append(parent)
                parent = parent.getparent()
            return ancestors
        

    【讨论】:

    • 对不起,我忘了说我用的是minidom,不是lxml。无论如何感谢您的回复。
    【解决方案2】:

    我找到了答案:

    def read_region(self, xml):
            doc = minidom.parse(xml)
            node = doc.getElementsByTagName("Zone")
            data_array = []
            for zone in node:
                zone_child = zone.getElementsByTagName("Zone")
                if len(zone_child)==0:
                    print(zone.getAttribute("name"))
                    subzone_parent = zone.parentNode
                    zone_parent = subzone_parent.parentNode
                    print(zone_parent.getAttribute("name"))
    
                    subzone_parent_parent = zone_parent.parentNode
                    zone_parent_parent = subzone_parent_parent.parentNode
                    print(zone_parent_parent.getAttribute("name"))
    
                    subzone_top = zone_parent_parent.parentNode
                    zone_top = subzone_top.parentNode
                    try:
                        print(zone_top.getAttribute("name"))
                    except Exception,e:
                        print("DEBUG")
    

    我检查 Zone 节点中没有子节点并获取该节点的每个父节点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多