Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# .NET
Hi
 
How to check xml document is blank or has values before xml.load(test.xml) ?
Im using the following code :
 
 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 21-Nov-11 16:57pm
Edited 21-Nov-11 17:45pm
AditSheth4.5K
v2
Comments
DepiyaReddy at 22-Nov-11 17:45pm
   
thanks.

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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
  Permalink  

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 518
1 OriginalGriff 459
2 ChintanShukla 305
3 Richard Deeming 275
4 RyanDev 230
0 Sergey Alexandrovich Kryukov 8,858
1 OriginalGriff 7,451
2 CPallini 2,603
3 Richard MacCutchan 2,095
4 Abhinav S 1,893


Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 22 Nov 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100