簡體   English   中英

Python xml遍歷n級標記

[英]Python xml iterate through n-level tags

我想迭代我的標簽的特定階段。

例如,我想迭代頂層對象:

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

我只想在第1階段迭代標簽(stage1tag和stage1tag2)在我的真實xml中,它們不被稱為child ... tag和stage ...標簽,這只是為了更好的可讀性。 我如何獲得頂級標簽? 我正在尋找類似的東西

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的根節點?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM