[Python] 将一个Etree XML结构转换为一个Python dict+list格式的代码 →→→→→进入此内容的聊天室

来自 , 2021-01-18, 写在 Python, 查看 112 次.
URL http://www.code666.cn/view/138aab28
  1. from lxml import etree, objectify
  2.  
  3. def formatXML(parent):
  4.     """                                                                                                      
  5.    Recursive operation which returns a tree formated                                                        
  6.    as dicts and lists.                                                                                      
  7.    Decision to add a list is to find the 'List' word                                                        
  8.    in the actual parent tag.                                                                                
  9.    """
  10.     ret = {}
  11.     if parent.items(): ret.update(dict(parent.items()))
  12.     if parent.text: ret['__content__'] = parent.text
  13.     if ('List' in parent.tag):
  14.         ret['__list__'] = []
  15.         for element in parent:
  16.             if element.tag is not etree.Comment:
  17.                 ret['__list__'].append(formatXML(element))
  18.     else:
  19.         for element in parent:
  20.             if element.tag is not etree.Comment:
  21.                 ret[element.tag] = formatXML(element)
  22.     return ret
  23. ## end of http://code.activestate.com/recipes/578244/ }}}
  24.  
  25. #//python/4509

回复 "将一个Etree XML结构转换为一个Python dict+list格式的代码"

这儿你可以回复上面这条便签

captcha