Вы можете использовать модифицированную версию этого примера из документов :
Попробуйте изменить maxDepth
и depth
в словари, использующие имя элемента (тег) для ключа ...
Python
from xml.etree.ElementTree import XMLParser
class MaxDepth: # The target object of the parser
maxDepth = {}
depth = {}
def start(self, tag, attrib): # Called for each opening tag.
try:
self.depth[tag] += 1
except KeyError:
self.depth[tag] = 0
self.maxDepth[tag] = 0
if self.depth[tag] > self.maxDepth[tag]:
self.maxDepth[tag] = self.depth[tag]
def end(self, tag): # Called for each closing tag.
self.depth[tag] -= 1
def data(self, data):
pass # We do not need to do anything with data.
def close(self): # Called when all data has been parsed.
return self.maxDepth
target = MaxDepth()
parser = XMLParser(target=target)
exampleXml = """
<chorus>
<l>Alright now lose it <ah>aah <i>aah <ah>a<ah>a</ah>h</ah> aah</i> aah</ah></l>
<l>Just lose it aah aah aah aah aah</l>
<l>Go crazy aah aah aah aah aah</l>
<l>Oh baby <ah>aah aah</ah>, oh baby baby <ah>aah aah</ah></l>
</chorus>"""
parser.feed(exampleXml)
print(parser.close())
Вывод
{'chorus': 0, 'l': 0, 'ah': 2, 'i': 0}
Отредактированный Python (где chorus
уже является ElementTree.Element
объектом)
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import XMLParser
class MaxDepth: # The target object of the parser
maxDepth = {}
depth = {}
def start(self, tag, attrib): # Called for each opening tag.
try:
self.depth[tag] += 1
except KeyError:
self.depth[tag] = 0
self.maxDepth[tag] = 0
if self.depth[tag] > self.maxDepth[tag]:
self.maxDepth[tag] = self.depth[tag]
def end(self, tag): # Called for each closing tag.
self.depth[tag] -= 1
def data(self, data):
pass # We do not need to do anything with data.
def close(self): # Called when all data has been parsed.
return self.maxDepth
exampleXml = """
<chorus>
<l>Alright now lose it <ah>aah <i>aah <ah>a<ah>a</ah>h</ah> aah</i> aah</ah></l>
<l>Just lose it aah aah aah aah aah</l>
<l>Go crazy aah aah aah aah aah</l>
<l>Oh baby <ah>aah aah</ah>, oh baby baby <ah>aah aah</ah></l>
</chorus>"""
chorus_element = ET.fromstring(exampleXml)
target = MaxDepth()
parser = XMLParser(target=target)
parser.feed(ET.tostring(chorus_element))
print(parser.close())