Mínimo implementación DOM:
Enlace: http://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom
Python proporciona una implementación estándar del W3C-llena de DOM XML (XML .dom) y uno mínimo, xml.dom.minidom. Este último es más simple y más pequeño que la implementación completa. Sin embargo, desde una "perspectiva de análisis", tiene todos los pros y contras del DOM estándar, es decir, carga todo en la memoria.
Considerando un archivo XML básica:
<?xml version="1.0"?>
<catalog>
<book isdn="xxx-1">
<author>A1</author>
<title>T1</title>
</book>
<book isdn="xxx-2">
<author>A2</author>
<title>T2</title>
</book>
</catalog>
Una posible analizador Python usando minidom es:
import os
from xml.dom import minidom
from xml.parsers.expat import ExpatError
#-------- Select the XML file: --------#
#Current file name and directory:
curpath = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(curpath, "sample.xml")
#print "Filename: %s" % (filename)
#-------- Parse the XML file: --------#
try:
#Parse the given XML file:
xmldoc = minidom.parse(filepath)
except ExpatError as e:
print "[XML] Error (line %d): %d" % (e.lineno, e.code)
print "[XML] Offset: %d" % (e.offset)
raise e
except IOError as e:
print "[IO] I/O Error %d: %s" % (e.errno, e.strerror)
raise e
else:
catalog = xmldoc.documentElement
books = catalog.getElementsByTagName("book")
for book in books:
print book.getAttribute('isdn')
print book.getElementsByTagName('author')[0].firstChild.data
print book.getElementsByTagName('title')[0].firstChild.data
Tenga en cuenta que xml.parsers.expat es una interfaz de Python para los expatriados analizador XML no validador (docs.python.org/2/library/pyexpat.html).
Los xml.dom paquete proporciona también la clase de excepción DOMException, pero no se supperted en minidom!
El elementtree API XML:
Enlace: http://docs.python.org/2/library/xml.etree.elementtree.html
elementtree es mucho más fácil de usar y requiere menos memoria que DOM XML. Además, está disponible una implementación de C (xml.etree.cElementTree).
Una posible analizador Python usando elementtree es:
import os
from xml.etree import cElementTree # C implementation of xml.etree.ElementTree
from xml.parsers.expat import ExpatError # XML formatting errors
#-------- Select the XML file: --------#
#Current file name and directory:
curpath = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(curpath, "sample.xml")
#print "Filename: %s" % (filename)
#-------- Parse the XML file: --------#
try:
#Parse the given XML file:
tree = cElementTree.parse(filename)
except ExpatError as e:
print "[XML] Error (line %d): %d" % (e.lineno, e.code)
print "[XML] Offset: %d" % (e.offset)
raise e
except IOError as e:
print "[XML] I/O Error %d: %s" % (e.errno, e.strerror)
raise e
else:
catalogue = tree.getroot()
for book in catalogue:
print book.attrib.get("isdn")
print book.find('author').text
print book.find('title').text
¡Gracias por mencionar las siguientes advertencias! (Resulta que necesito ambos en mi proyecto). "Soporte de XPath ... ElementTree se desvía de DOM, donde los nodos tienen acceso a sus padres y hermanos". –