Ver Mensaje Individual
  #1 (permalink)  
Antiguo 22/11/2011, 17:53
aarias1978
 
Fecha de Ingreso: octubre-2011
Mensajes: 9
Antigüedad: 12 años, 6 meses
Puntos: 1
Serializar XML en Python

Buenas... Preciso me de una mano con la serialización de xml en python, preciso crear desde un archivo xml todos los objetos pertinentes, y al reves desde un objeto python crear el xml.

He estado haciendo lo siguiente:

Código Python:
Ver original
  1. class XML2Py():
  2.  
  3.     def __init__( self ):
  4.  
  5.         self._parser = parser = etree.XMLParser( remove_blank_text=True )
  6.         self._root = 'DHA'  # root de la estructura etree
  7.         self.data = 'Nivel'   # Estructura donde precesamos los datos Python
  8.  
  9.     def parse( self, xmlString ):
  10.         '''        procesa string xml dentro de una estructura de datos Python
  11.        '''
  12.         self._root = etree.fromstring( xmlString, self._parser )
  13.         self.data = self._parseXMLRoot()
  14.         return self.data
  15.  
  16.     def tostring( self ):
  17.         '''
  18.        crea una representación de string usando el objeto etree
  19.        '''
  20.         if self._root != None:
  21.             return etree.tostring( self._root )
  22.  
  23.     def _parseXMLRoot( self ):
  24.         '''
  25.        comienza a procesar, tener cuidado en el primer nivel de serializacion
  26.        '''
  27.         childDict = self._parseXMLNode( self._root )
  28.         return { self._root.tag : childDict["children"] }
  29.  
  30.     def _parseXMLNode( self, element ):
  31.         '''
  32.        resto del procesamiento
  33.        '''
  34.         childContainer = None # either Dict or List
  35.  
  36.         # process any tag attributes
  37.         # if we have attributes then the child container is a Dict
  38.         #   otherwise a List
  39.         if element.items():
  40.             childContainer = {}
  41.             childContainer.update( dict( element.items() ) )
  42.         else:
  43.             childContainer = []
  44.  
  45.  
  46.         if isinstance( childContainer, list ) and element.text:
  47.             # tag with no attributes and one that contains text
  48.             childContainer.append( element.text )
  49.  
  50.         else:
  51.             # tag might have children, let's process them
  52.             for child_elem in element.getchildren():
  53.  
  54.                 childDict = self._parseXMLNode( child_elem )
  55.  
  56.               # let's store our child based on container type
  57.                 #
  58.                 if isinstance( childContainer, dict ):
  59.                     # these children are lone tag entities ( eg, 'copyright' )
  60.                     childContainer.update( { childDict["tag"] : childDict["children"] } )
  61.  
  62.                 else:
  63.                     # these children are repeated tag entities ( eg, 'format' )
  64.                     childContainer.append( childDict["children"] )
  65.  
  66.         return { "tag":element.tag, "children": childContainer }
  67.  
  68.  
  69. def main():
  70.  
  71.     archivoxml = minidom.parse('tentativoXML.xml') # Uso la función par de minidom para cargar en una variable el contenido del archivo xml
  72.     xml_string = archivoxml.toxml() # Paso los datos del archivo para sean procesados como string
  73.     deserializer = XML2Py()
  74.     python_object = deserializer.parse( xml_string )
  75.     print xml_string
  76.     print python_object
  77.  
  78. if __name__ == '__main__':
  79.     main()

Pero me genera problemas, ya que me quedan elementos a los cuales no les deja el nombre del tag, sino que les pone un numero.



Espero puedan ayudar. Saludos

Última edición por AlvaroG; 23/11/2011 a las 12:04 Razón: coloreado de código