Click here to Skip to main content
15,896,338 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
How to check xml document is blank or has values before xml.load(test.xml) ?
Im using the following code :
C#
XmlDocument xml = new XmlDocument();
xml.Load("test.xml");

it throws the following error when the xml document is blank :
"Root element is missing."


thanks
Posted
Updated 21-Nov-11 17:45pm
v2
Comments
DepiyaReddy 22-Nov-11 17:45pm    
thanks.

1 solution

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.

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.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900