第一次在Python中解析XML:这可能不像它本来的那样,可以吗?

时间:2014-01-31 16:19:55

标签: python xml elementtree

我需要从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?

1 个答案:

答案 0 :(得分:0)

试着看一下llml库的例子。 (look here)具体来说,我想你想看一下XPath函数