Search code examples
c#xmlxmldocument

How to check if a LoadXml() on a XmlDocument instance went wrong without using XmlException


I have to fix some code that looks like this:

XmlDocument XmlFoo = null;

try{
    SomeUntrappedWCFCalls();
    SomeUntrappedStringParsing();
    SomeUntrappedXMLParsing();
    ..
    XmlFoo = new XmlDocument();
    XmlFoo.LoadXml(SomeXml);
    ..
    SomeUntrappedWCFCalls();
    SomeUntrappedStringParsing();
    SomeUntrappedXMLParsing();
}
(Exception ex){

      CodeThatDealsWithPartOfTheExceptionsRaisedAbove(); 
      ..
      //Need to check if the LoadXml() went wrong
      ..
      CodeThatDealsWithPartOfTheExceptionsRaisedAbove();
}

How could I properly check in the exception handling section (*), if XmlFoo is a new instance of XmlDocument but the LoadXml() went wrong for a load/parse error?

I have two constrains:

  1. I can't wrap the LoadXML() inside an XmlException because all the error handling are handled inside the Exception code.
  2. I can't create an XmlException just before the general Exception because there are other Xml files parsed before and after the XmlFoo parsing.

Is it a safe and inelegant workaround to just count the number of Nodes with something like:

if (XmlFoo.ChildNodes.Count == 0){..

or do I need some other variables to check the LoadXML() parsing status in some way?


Solution

  • Given your horrible constraints, I would view the cleanest solution as:

    bool parsingAttempted = false;
    bool parsingSucceeded = false;
    try
    {
        XmlFoo = new XmlDocument();
        parsingAttempted = true;
        XmlFoo.LoadXml(SomeXml);
        parsingSucceeded = true;
    }
    

    Now you can check for three situations:

    • Error before parsing was attempted: parsingAttempted is false
    • Error during parsing: parsingAttempted is true, parsingSucceeded is false
    • Parsing succeeded: parsingSucceeded is true