Domanda

Devo convalidare una stringa XML (e non un file) rispetto a un file di descrizione DTD.

Come è possibile farlo? python?

È stato utile?

Soluzione

Un'altra buona opzione è convalida di lxml che trovo abbastanza piacevole da usare.

Un semplice esempio tratto dal sito 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

Altri suggerimenti

dalla directory degli esempi nei collegamenti 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top