How to check xml document is blank or has values before xml.load(test.xml) ?
Im using the following code :
XmlDocument xml = new XmlDocument();
it throws the following error when the xml document is blank :
"Root element is missing.
First, let's put it correctly. "Root element is missing" is not an "empty document", this is not an XML document. There is no such concept as "empty" XML document.—SA
Instead of "detecting", you need to sort out how a text not well-formed as XML could sneak in this file and address this problem.
However, if there is a valid scenario when the text can be either XML or some "random" text (even empty string; however, if an empty string or "almost empty" (some string which becomes empty after
string.Trim()), read the stream in a string first and compare with
string.Empty or check
string.IsNullOrEmpty), the exception you describe (exception, not error) is a sufficient and valid indication of the problem. Catch all XML exceptions in some try-catch block, identify the problem and process this case accordingly.
But finding a root cause and making sure the file always contains XML would be much better. As to exceptions, they always should be caught, but all of them should be caught only on the top of stack of each thread, and in the main cycle of the UI.
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)