Je dois valider une chaîne XML (et non un fichier) par rapport à un fichier de description DTD.Comment valider xml sur un fichier DTD en Python
Comment cela peut-il être fait en python
?
Je dois valider une chaîne XML (et non un fichier) par rapport à un fichier de description DTD.Comment valider xml sur un fichier DTD en Python
Comment cela peut-il être fait en python
?
Une autre bonne option est lxml's validation que je trouve très agréable à utiliser.
Un exemple simple tiré du site 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
à partir du répertoire des exemples dans les liaisons python libxml2:
#!/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
Notez que les liaisons libxml2 ne font pas partie de la bibliothèque standard Python, c'est-à-dire non construit. – ChuckB