使用Python的ElementTree .iter()时保持父子关系

时间:2016-11-21 12:46:04

标签: python relationship parent elementtree

我有以下标记:

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

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

void savePoints(QVector<QPoint> points)
{
    QFile file("points.bin");
    if(file.open(QIODevice::WriteOnly))
    {
        QDataStream out(&file);
        out.setVersion(QDataStream::Qt_4_0);
        out << points;
        file.close();
    }
}

QVector<QPoint> loadPoints()
{
    QVector<QPoint> points;
    QFile file("points.bin");
    if(file.open(QIODevice::ReadOnly))
    {
        QDataStream in(&file);
        in.setVersion(QDataStream::Qt_4_0);
        in >> points;
        file.close();
    }
    return points;
}

我需要找到一种方法来保持父母和孩子之间的关系,例如,我想知道&#34; f&#34;父母是&#34; a&#34;。我现在能想到的唯一方法是每次找到父节点时: len(list(elem))&gt; 0 ,我将该节点添加到列表中并跟踪当前的&#34;级别&#34;用于建立该关系的节点。我没有发现这个解决方案非常优雅,我确信有一个更简单的解决方案,不幸的是我还没有找到它:/,我希望有人可以对我有所了解:d

PS。在有人发表评论之前&#34;在你询问之前使用搜索&#34;,我已经阅读过每一篇文章,这些帖子在某种程度上与我尝试做的事情有关,例如:

碰巧它们是特定于用例的并且对我没有帮助,或者至少我没有找到将他们的解决方案连接到我的方法。

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用字典,这更适合树状结构。目标是将字典的键作为父级,值是子级列​​表。这是你如何做到的:

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))

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

在行动here中查看。只需确保您的XML有效。