missingfaktor
missingfaktor

Reputation: 92066

Catch an error in case of bad XML

I am using xml.dom.minidom for parsing some XML from a string. I need to handle an error case when the supplied XML is malformed. What error do I catch?

In other words, what should replace BadXml below?

try:
    from xml.dom import minidom
    in_xml = minidom.parseString(some_string)
except BadXml:
    handle_bad_xml(some_string)

Upvotes: 3

Views: 4467

Answers (2)

Nick Bastin
Nick Bastin

Reputation: 31339

Ultimately the only answer is that you must catch Exception. minidom does not implement DOMException, and while it does use some general exceptions from xml.dom, it also freely uses TypeError and other standard python exceptions whose only single common base is Exception itself.

Upvotes: 2

John Keyes
John Keyes

Reputation: 5604

I think this is what you want:

from xml.parsers.expat import ExpatError

try:
    from xml.dom import minidom
    in_xml = minidom.parseString(some_string)
except ExpatError:
    handle_bad_xml(some_string)

Upvotes: 4

Related Questions