[英]Keeping parent-child relationships when using Python's ElementTree .iter()
我有以下標記:
<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
附: 在有人評論“先用搜索再問”之前,我已經閱讀了每一篇在某種程度上與我正在嘗試做的事情相關的帖子,例如:
碰巧它們是針對特定用例的,並沒有完全幫助我,或者至少我沒有找到將他們的解決方案連接到我的解決方案的方法。
提前致謝
您可以使用字典,這對樹狀結構更有利。 目標是字典的鍵是父級,值是子級列表。 您可以這樣做:
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
返回的。
在這里查看它的實際效果。 只要確保您的 XML 是有效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.