Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 494
fulmicoton Avatar asked Aug 19 '08 06:08

fulmicoton


People also ask

How a XML document is validated What is DTD?

If an XML document is well-formed and has an associated Document Type Declaration (DTD), then it is said to be a valid XML document.

When an XML document validated against a DTD is both?

An XML document with correct syntax is called "Well Formed". An XML document validated against a DTD is both "Well Formed" and "Valid".

Which browser can validate your XML against a DTD?

Can a browser such as Internet Explorer use DTDs to validate XML documents? Yes, but not by default. By default, Internet Explorer can use XML schemas and displays the results when loading a document.


1 Answers

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/>") 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 
like image 192
Michael Twomey Avatar answered Sep 29 '22 04:09

Michael Twomey