【问题标题】:Keeping parent-child relationships when using Python's ElementTree .iter()使用 Python 的 ElementTree .iter() 时保持父子关系
【发布时间】:2016-11-21 12:46:04
【问题描述】:

我有以下标记:

<a>
  <b>
    <c>
    <d>
    <e>
  </b>
  <f>
    <g>
  </f>
</a>

使用 ElementTree 函数 .iter() 我得到类似:

a, b, c, d, e, f, g

我需要找到一种方法来保持父母和孩子之间的关系,例如,我想知道“f”父母是“a”。到目前为止,我能想到的唯一方法是每次找到父节点时:len(list(elem)) > 0,我将该节点添加到列表中并跟踪当前的“级别" 的节点来建立这种关系。我觉得这个解决方案不是很优雅,我确信有一个更简单的解决方案,不幸的是我还没有找到它:/,我希望有人能对我有所启发:D

ps。在有人“在你问之前使用搜索”之前,我已经阅读了每一篇在某种程度上与我正在尝试做的事情相关的帖子,比如:

碰巧他们是非常具体的用例,对我没有太大帮助,或者至少我没有找到将他们的解决方案与我的解决方案联系起来的方法。

提前致谢

【问题讨论】:

  • 使用字典?父母是关键,孩子是价值。如果孩子只能有一个父母,这在 XML 中应该是正确的。
  • 以我的标记为例,在我的例子中,我可以让 出现在 中,这种情况并不常见,但它可能会发生。

标签: python relationship parent elementtree


【解决方案1】:

您可以使用字典,它更适合树状结构。目标是让字典的键成为父级,值是子级列​​表。你可以这样做:

def get_children(parent):
    return [child for child in parent]

def get_parent_children_mapping(tree):
    return {parent: get_children(parent) for parent in tree.iter()}

示例用法如下:

import xml.etree.ElementTree as ET

def get_children(parent):
    return [child for child in parent]

def get_parent_children_mapping(tree):
    return { parent: get_children(parent) for parent in tree.iter() }

if __name__ == "__main__":

    s = """
    <a>
      <b>
        <c>Hello</c>
        <d>World</d>
        <e>Goodbye</e>
      </b>
      <f>
        <g>Hmmm...</g>
        <c>Hello</c>
      </f>
    </a>
    """

    tree = ET.fromstring(s)

    for parent, children in get_parent_children_mapping(tree).items():
        if children:
            print("{0} -> {1}".format(parent, children))

您会发现根元素被省略了——这是因为它显然没有父元素,但它的子元素是整个树上从get_parent_children_mapping 返回的所有元素。

看到它在行动here。只需确保您的 XML 有效。

【讨论】:

  • 如果一个节点可能出现重复会发生什么?这可能发生在孩子和父母身上(以我为例)
  • 如果有嵌套,你将不得不使用递归。你的例子没有,所以我没有添加。
  • 我对我的代码进行了测试,父子关系似乎都被打乱了。我不能在我的代码中使用它,因为我需要对节点进行排序(深度优先样式),这也是我起初认为列表格式很酷的原因之一。
  • @VitorMexia 看看collections.OrderedDict
猜你喜欢
  • 2021-12-05
  • 2019-03-26
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 2015-03-16
相关资源
最近更新 更多