创建 "while still child marker loop" etree Python
Create a "while still child marker loop" etree Python
我想知道如何使用 Python 中的库 Element Tree
创建 while 循环,如下所示:
while there is still child marker :
cross each marker
因为我有一个由软件生成的 XML 文件,但它可以是:
<root
<child1
<child2
<child1
<child2
可以这样:
<root
<child1
<child2
<child3
<child1
<child2
<child3
没有 while
循环我必须为每种情况做不同的代码
感谢您的帮助。
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
>>>
我想知道如何使用 Python 中的库 Element Tree
创建 while 循环,如下所示:
while there is still child marker :
cross each marker
因为我有一个由软件生成的 XML 文件,但它可以是:
<root
<child1
<child2
<child1
<child2
可以这样:
<root
<child1
<child2
<child3
<child1
<child2
<child3
没有 while
循环我必须为每种情况做不同的代码
感谢您的帮助。
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
>>>