Ver Mensaje Individual
  #2 (permalink)  
Antiguo 07/08/2012, 13:32
Avatar de razpeitia
razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Obtener valor de un XML

Te recomendaría usar lxml junto con xpaths para parsear los datos de forma mas rápida y eficiente.

Código Python:
Ver original
  1. from xml.dom import minidom
  2.  
  3. def getText(nodelist):
  4.     rc = []
  5.     for node in nodelist:
  6.         if node.nodeType == node.TEXT_NODE:
  7.             rc.append(node.data)
  8.     return ''.join(rc)
  9.  
  10. def obtenerStock(referencia):
  11.     try:
  12.         #encontramos el fichero de stock
  13.         xmlstock = minidom.parse("a.xml")
  14.         articulos = xmlstock.getElementsByTagName("articulo")
  15.         for articulo in articulos:
  16.             if referencia == articulo.attributes['ref'].value:
  17.                  stocks = articulo.getElementsByTagName("stock_disponible")
  18.                  stock = stocks[0]
  19.                  stock = int(getText(stock.childNodes))
  20.                  return stock
  21.             else:
  22.                  stock = 0
  23.     except ValueError:
  24.         print "No se ha encontrado el fichero de stocks..."
  25.  
  26. print obtenerStock('10130')
  27. print obtenerStock('11096')

Código XML:
Ver original
  1. <?xml version='1.0'?>
  2. <articulos>
  3.     <articulo ref='10130'>
  4.         <stock_disponible>2</stock_disponible>
  5.     </articulo>
  6.  
  7.     <articulo ref='11096'>
  8.         <stock_disponible>6</stock_disponible>
  9.     </articulo>
  10. </articulos>