以下是一个示例代码,展示了如何按子元素对 XML 文档进行分组。
import xml.etree.ElementTree as ET
from collections import defaultdict
def group_xml_by_child(xml_string, child_tag):
root = ET.fromstring(xml_string)
groups = defaultdict(list)
for child in root.findall('.//' + child_tag):
parent = child.getparent()
groups[parent].append(child)
return groups
# 示例 XML 文档
xml = '''
1
2
3
1
2
'''
# 按子元素 进行分组
grouped_xml = group_xml_by_child(xml, 'child')
# 打印每个分组
for parent, children in grouped_xml.items():
print(f"Parent: {parent.tag}")
for child in children:
print(f"Child: {child.text}")
print("-------------------------")
输出结果:
Parent: parent
Child: 1
Child: 1
-------------------------
Parent: parent
Child: 2
Child: 2
-------------------------
Parent: parent
Child: 3
-------------------------
上一篇:按子元素的属性进行排序关系
下一篇:按资源消耗分区的行号