如何迭代与当前元素同名的 XML 子元素并避免迭代中的当前元素?

问题描述 投票:0回答:1

我有

对于节点及其直接子节点具有相同名称的给定 XML(不能更改命名),在这里 items

我要

只对孩子进行迭代,有一个 items 字段的 description

我的问题

迭代中出现了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)
print(">>", tree.find("items"))
for item in tree.find("items").iter("items"):
    print(item, item.find("description"))

电流输出

>> <Element 'items' at 0x0000020B5CBF8720>
<Element 'items' at 0x0000020B5CBF8720> None
<Element 'items' at 0x0000020B5CBF8770> <Element 'description' at 0x0000020B5CBF87C0>
<Element 'items' at 0x0000020B5CBF8810> <Element 'description' at 0x0000020B5CBF8860>

预期产出

>> <Element 'items' at 0x0000020B5CBF8720>
<Element 'items' at 0x0000020B5CBF8770> <Element 'description' at 0x0000020B5CBF87C0>
<Element 'items' at 0x0000020B5CBF8810> <Element 'description' at 0x0000020B5CBF8860>
python xml elementtree
1个回答
0
投票

将 XPath 与 findall() 结合使用。

tree.findall('items/items')
© www.soinside.com 2019 - 2024. All rights reserved.