Создайте петлю маркера «пока еще ребенок» etree Python - PullRequest
0 голосов
/ 21 мая 2019

Я хотел бы знать, как я могу создать цикл while с библиотекой Element Tree в Python, который выглядит следующим образом:

while there is still child marker :
    cross each marker

Поскольку у меня есть файл XML, который генерируется программным обеспечением, но это может быть:

<root
    <child1
        <child2
    <child1
        <child2

как может быть:

<root
    <child1
        <child2
            <child3
    <child1
        <child2
            <child3

Без цикла while мне приходится делать разные коды для каждого случая

Спасибо за помощь.

1 Ответ

0 голосов
/ 21 мая 2019

Метод Element.iter () сначала пройдет глубину потомков элементов

import xml.etree.ElementTree as ET

s = '''
<root>
    <child1>
        <child2>
            <child3></child3>
        </child2>
    </child1>
    <child1>
        <child2></child2>
    </child1>
</root>'''


root = ET.fromstring(s)

Использование:

>>> for c in root.iter():
...     print(c.tag)

root
child1
child2
child3
child1
child2

>>> e = root.find('child1')
>>> for c in e.iter():
...     print(c.tag)

child1
child2
child3

Дерево, где все элементы имеют одинаковое имя .

s = '''
<root foo='0'>
    <child1 foo='1'>
        <child1 foo='2'>
            <child1 foo='3'></child1>
        </child1>
    </child1>
    <child1 foo='4'>
        <child1 foo='5'></child1>
    </child1>
</root>'''

root = ET.fromstring(s)

>>> for e in root.iter():
...     print(e.tag, e.attrib['foo'])

root 0
child1 1
child1 2
child1 3
child1 4
child1 5
>>>
...