Search code examples
c#xmlstringcharacter-encodingxmlexception

Catch only character encoding issues in XmlException


I'm using System.Xml to parse xml documents. Sometimes the xml documents contain unencodable characters and then an XmlException gets thrown. In those cases, I want to retry parsing the document with a forced encoding, like this:

try {
    var doc = new XmlDocument();
    doc.Load()
} catch (XmlException xe) {
    // Retry here with another encoding..
}

This works fairly well except that XmlException gets thrown for all types of xml problems even those not caused by character encoding issues. In those cases I do not want to retry parsing. So is there a way to figure out whether the XmlException was caused by character encoding problems or something else?


Solution

  • I guess the answer is no, there is no way to robustly find out what caused the XmlException.