• 4

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

How do I validate xml against a DTD file in Python

I need to validate an XML string (and not a file) against a DTD description file.

How can that be done in python?

Another good option is lxml's validation which I find quite pleasant to use.

A simple example taken from the lxml site:

from StringIO import StringIO

from lxml import etree

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

root = etree.XML("<foo>bar</foo>")
# False
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content
  • 31
Reply Report

from the examples directory in the libxml2 python bindings:

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

# Memory debug specific

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

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"

del dtd
del ctxt
  • 7
Reply Report
    • Note that the libxml2 bindings are not part of the Python standard library, i.e. not built in.

Trending Tags