如何遍历与当前元素同名的XML子元素并排除当前元素
解决XML中同名父/子节点的遍历问题
给定XML文档存在父节点items与直接子节点items同名的情况,需要仅遍历带有description字段的子级items元素,但使用iter方法会将父级items也包含在结果中。
方法1:遍历直接子节点并筛选
直接获取父级items的直接子元素,筛选出符合条件的节点,这种方式更直接高效,适合仅需处理直接子级的场景:
from xml.etree import ElementTree content = """<?xml version="1.0" encoding="utf-8"?> <root> <items> <items> <description>foo1</description> </items> <items> <description>foo2</description> </items> </items> </root> """ tree = ElementTree.fromstring(content) parent_items = tree.find("items") print(">>>", parent_items) # 遍历父items的直接子节点,筛选出带description的items元素 for item in parent_items: if item.tag == "items" and item.find("description") is not None: print(item, item.find("description"))
方法2:使用iter并排除父节点本身
如果需要遍历所有后代的items节点(不限于直接子级),可以在iter遍历后排除父节点本身:
from xml.etree import ElementTree content = """<?xml version="1.0" encoding="utf-8"?> <root> <items> <items> <description>foo1</description> </items> <items> <description>foo2</description> </items> </items> </root> """ tree = ElementTree.fromstring(content) parent_items = tree.find("items") print(">>>", parent_items) for item in parent_items.iter("items"): # 跳过父节点本身 if item is not parent_items: print(item, item.find("description"))
原问题原因
调用element.iter("items")时,会从当前节点(父级items)开始,递归遍历所有后代中标签为items的节点,因此父节点自身会被包含在迭代结果里。
内容的提问来源于stack exchange,提问作者azro
相关产品推荐
相关产品推荐

