Skip to content

Instantly share code, notes, and snippets.

@jl2
Created April 19, 2011 17:31
Show Gist options
  • Save jl2/928952 to your computer and use it in GitHub Desktop.
Save jl2/928952 to your computer and use it in GitHub Desktop.
Use lxml and Python3 to validate XML against a DTD.The DTD can be specified on the command line, or as an optional parameter to the script.
#!/usr/bin/env python3
# Use lxml to validate XML against a DTD
import re
import sys
import os.path
import codecs
from lxml import etree
def main(args):
if len(args)<1:
print("Not enough arguments given. Expected:")
print("\tvalidatexml <xml file name> [<dtd file name>]\n")
exit(1)
dtdRe = re.compile('.*<!DOCTYPE .* ["\'](.*\.dtd)["\']>.*')
theDtd = None
inFile = args[0]
fdir = os.path.abspath(os.path.dirname(inFile))
if len(args)==2:
theDtd = os.path.abspath(args[1])
else:
with codecs.open(args[0], 'r', 'utf-8') as inf:
for ln in inf:
mtch = dtdRe.match(ln)
if mtch:
if os.path.isabs(mtch.group(1)):
theDtd = mtch.group(1)
else:
theDtd = os.path.abspath(fdir + '/' + mtch.group(1))
break
if theDtd is None:
print("No DTD specified!")
exit(2)
if not os.path.exists(theDtd):
print("The DTD ({}) does not exist!".format(theDtd))
exit(3)
print('Using DTD:', theDtd)
parser = etree.XMLParser(dtd_validation=True)
dtd = etree.DTD(open(theDtd))
tree = etree.parse(args[0])
valid = dtd.validate(tree)
if (valid):
print("XML was valid!")
else:
print("XML was not valid:")
print(dtd.error_log.filter_from_errors())
if __name__ == '__main__':
main(sys.argv[1:])
@WISSaab
Copy link

WISSaab commented Feb 27, 2025

Can't parse xml file without the DTD fixing up the character entities first. Otherwise you get errors like Ø not recognised.
Is there a way to pass the external DTD file reference to the parser to say use this DTD?
This is so you can use an external DTD file on an xml file that doesn't have a reference to the DTD in its xml?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment