Question

J'ai besoin de valider une chaîne XML (et non un fichier) par rapport à un fichier de description DTD.

Comment cela peut-il être fait dans python?

Était-ce utile?

La solution

Une autre bonne option est validation de lxml que je trouve assez 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

Autres conseils

à partir du répertoire examples 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top