2008-08-19 21 views

Respuesta

29

Otra buena opción es lxml's validation que me parece bastante agradable de usar.

Un ejemplo sencillo tomado del sitio lxml:

from StringIO import StringIO 

from lxml import etree 

dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>""")) 
root = etree.XML("<foo/>") 
print(dtd.validate(root)) 
# True 

root = etree.XML("<foo>bar</foo>") 
print(dtd.validate(root)) 
# False 
print(dtd.error_log.filter_from_errors()) 
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content 
7

desde el directorio de ejemplos en los enlaces libxml2 pitón:

#!/usr/bin/python -u 
import libxml2 
import sys 

# Memory debug specific 
libxml2.debugMemory(1) 

dtd="""<!ELEMENT foo EMPTY>""" 
instance="""<?xml version="1.0"?> 
<foo></foo>""" 

dtd = libxml2.parseDTD(None, 'test.dtd') 
ctxt = libxml2.newValidCtxt() 
doc = libxml2.parseDoc(instance) 
ret = doc.validateDtd(ctxt, dtd) 
if ret != 1: 
    print "error doing DTD validation" 
    sys.exit(1) 

doc.freeDoc() 
dtd.freeDtd() 
del dtd 
del ctxt 
+0

Tenga en cuenta que los enlaces libxml2 no son parte de la biblioteca estándar de Python, es decir, no incorporado. – ChuckB

Cuestiones relacionadas