Checking XML Well-Formedness
Credit: Paul Prescod
Problem
You need to check if an XML document is well-formed (not if it conforms to a DTD or schema), and you need to do this quickly.
Solution
SAX (presumably using a fast parser such as Expat underneath) is the fastest and simplest way to perform this task:
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
from glob import glob
import sys
def parsefile(file):
parser = make_parser( )
parser.setContentHandler(ContentHandler( ))
parser.parse(file)
for arg in sys.argv[1:]:
for filename in glob(arg):
try:
parsefile(filename)
print "%s is well-formed" % filename
except Exception, e:
print "%s is NOT well-formed! %s" % (filename, e)Discussion
A text is a well-formed XML document if it adheres to all the basic syntax rules for XML documents. In other words, it has a correct XML declaration and a single root element, all tags are properly nested, tag attributes are quoted, and so on.
This recipe uses the SAX API with a dummy
ContentHandler that does nothing. Generally, when
we parse an XML document with SAX, we use a
ContentHandler
instance to process the document’s contents. But in
this case, we only want to know if the document meets the most
fundamental syntax constraints of XML; therefore, there is no
processing that we need to do, and the do-nothing handler suffices.
The
parsefile function parses the whole document and throws an exception if there is an error. The recipe’s main code catches any such exception and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access