我需要从XML文件中读取数据并使用ElementTree。读取许多节点看起来像这个ATM:
def read_edl_ev_ids(xml_tree):
# Read all EDL events (those which start with "EDL_EV_") from XML
# and put them into a dict with
# symbolic name as key and number as value. The XML looks like:
# <...>
# <COMPU-METHOD>
# <SHORT-NAME>DT_EDL_EventType</SHORT-NAME>
# <...>
# <COMPU-SCALE>
# <LOWER_LIMIT>number</LOWER-LIMIT>
# <....>
# <COMPU-CONST>
# <VT>EDL_EV_symbolic_name</VT>
# </COMPU-CONST>
# </COMPU-SCALE>
# </COMPU-METHOD>
edl_ev = {}
for node in xml_tree.findall('.//COMPU-METHOD'):
if node.find('./SHORT-NAME').text() == 'DT_EDL_EventType':
for subnode in node.findall('.//COMPU-SCALE'):
lower_limit = subnode.find('./LOWER-LIMIT').text()
edl_ev_name = subnode.find('./COMPU-CONST/VT').text()
if edl_ev_name.startswith('EDL_EV_'):
edl_ev[edl_ev_name] = lower_limit or '0'
return edl_ev
总结一下:我不喜欢它。它显然是一个XML解析初学者代码,丑陋/乏味,难以维护/不灵活/ DRY违反/等等......是否有更好的(声明性的)方式来读取XML?