Hacemos una verificación profunda cada secciones en nuestra página web con el objetivo de mostrarte siempre la información certera y actual.
Ejemplo: Python convierte XML a diccionario
from xml.etree import cElementTree as ElementTree
classXmlListConfig(list):def__init__(self, aList):for element in aList:if element:# treat like dictiflen(element)==1or element[0].tag != element[1].tag:
self.append(XmlDictConfig(element))# treat like listelif element[0].tag == element[1].tag:
self.append(XmlListConfig(element))elif element.text:
text = element.text.strip()if text:
self.append(text)classXmlDictConfig(dict):'''
Example usage:
>>> tree = ElementTree.parse('your_file.xml')
>>> root = tree.getroot()
>>> xmldict = XmlDictConfig(root)
Or, if you want to use an XML string:
>>> root = ElementTree.XML(xml_string)
>>> xmldict = XmlDictConfig(root)
And then use xmldict for what it is... a dict.
'''def__init__(self, parent_element):if parent_element.items():
self.update(dict(parent_element.items()))for element in parent_element:if element:# treat like dict - we assume that if the first two tags# in a series are different, then they are all different.iflen(element)==1or element[0].tag != element[1].tag:
aDict = XmlDictConfig(element)# treat like list - we assume that if the first two tags# in a series are the same, then the rest are the same.else:# here, we put the list in dictionary; the key is the# tag name the list elements all share in common, and# the value is the list itself
aDict =element[0].tag: XmlListConfig(element)# if the tag has attributes, add those to the dictif element.items():
aDict.update(dict(element.items()))
self.update(element.tag: aDict)# this assumes that if you've got an attribute in a tag,# you won't be having any text. This may or may not be a # good idea -- time will tell. It works for the way we are# currently doing XML configuration files...elif element.items():
self.update(element.tag:dict(element.items()))# finally, if there are no child tags and no attributes, extract# the textelse:
self.update(element.tag: element.text)
Si te sientes motivado, tienes la libertad de dejar un escrito acerca de qué le añadirías a este artículo.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)