Python-xml遍历n级标记



我想遍历标记的特定阶段。

例如,我想遍历顶层对象:

<stage1tag>
<child1tag>bla</child1tag>
<child2tag>blabla</child2tag>
<child3tag><stage2tag>heyho</stage2tag></child3tag></stage1tag>
<stage1tag2>
<stage1tag>
<child1tag>…
...

我只想在第1阶段(stage1tag和stage1tag2)迭代标记。在我真正的xml中,它们不被称为child。。。标记和阶段。。。标记,这只是为了更好的可读性。如何获取顶级标签?我正在搜索类似的东西

elems = mytree.getlevel(0) #toplevel
for child in elems.iter():
    #do something with the childs...

这是这个问题的一个可能的解决方案,我还没有对它进行广泛的测试,但它旨在让您了解如何处理这类问题。

import re
txt = 
'''
<stage1tag>
<child1tag>bla</child1tag>
<child2tag>blabla</child2tag>
<child3tag><stage2tag>heyho</stage2tag></child3tag></stage1tag>
<stage1tag2>
<stage1tag>
<child1tag>
'''
#1: find tags
re1='(<[^>]+>)' # regex string
rg = re.compile(re1,re.IGNORECASE|re.DOTALL)
tags = rg.findall(txt)
#2: determine the level of each tag
lvl = 1 # starting lvl
for t in tags:
    if '</' not in t: #it's an open tag, go up one lvl
        k = t[1:-1]
        print k,':',lvl
        lvl += 1
    else: #it's a close tag, go one lvl down
        lvl -= 1

打印出来:

stage1tag : 1
child1tag : 2
child2tag : 2
child3tag : 2
stage2tag : 3
stage1tag2 : 1
stage1tag : 2
child1tag : 3

考虑到你的xlm,这是正确的。

我假设您有一个根元素,否则解析器将被类似"XMLSyntaxError:文档末尾的额外内容"之类的内容阻塞。如果你缺少一个根元素,只需添加一个:

data = """<root>
<stage1tag id="1">
<child1tag>bla</child1tag>
<child2tag>blabla</child2tag>
<child3tag><stage2tag>heyho</stage2tag></child3tag>
</stage1tag>
<stage1tag id="2">
<child1tag>bla</child1tag>
<child2tag>blabla</child2tag>
<child3tag><stage2tag>heyho</stage2tag></child3tag>
</stage1tag>
</root>
"""

您可以使用lxml:

>>> import lxml.etree
>>> root = lxml.etree.fromstring(data)
>>> root.getchildren()
[<Element stage1tag at 0x3bf6530>, <Element stage1tag at 0x3bfb7d8>]
>>> for tag in root.getchildren():
        print(tag.attrib.get('id'))
1 
2

如果您的文档缺少一个根元素,我认为您不能称之为XML,那么您就有类似XML的东西(请参阅是否总是必须有一个带有XML.xsd的根节点?)

最新更新