Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python xml.dom.minidom.parse() function ignores DTDs

Tags:

python

xml

I have the following Python code:

import xml.dom.minidom
import xml.parsers.expat

try:
    domTree = ml.dom.minidom.parse(myXMLFileName)
except xml.parsers.expat.ExpatError, e:
    return e.args[0]

which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it completely ignores the DTD specified at the top of the XML file:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE ServerConfig SYSTEM "ServerConfig.dtd">

so it doesn't notice when mandatory elements are missing, for example. How can I switch on DTD checking?

like image 600
Charles Anderson Avatar asked Dec 23 '22 13:12

Charles Anderson


2 Answers

See this question - the accepted answer is to use lxml validation.

like image 178
gimel Avatar answered Dec 28 '22 11:12

gimel


Just by way of explanation: Python xml.dom.minidom and xml.sax use the expat parser by default, which is a non-validating parser. It may read the DTD in order to do entity replacement, but it won't validate against the DTD.

gimel and Tim recommend lxml, which is a nicely pythonic binding for the libxml2 and libxslt libraries. It supports validation against a DTD. I've been using lxml, and I like it a lot.

like image 30
ChuckB Avatar answered Dec 28 '22 10:12

ChuckB