Click here to Skip to main content
13,143,008 members (54,163 online)
Rate this:
Please Sign up or sign in to vote.
See more:

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."

Posted 21-Nov-11 16:57pm
Updated 21-Nov-11 17:45pm
DepiyaReddy 22-Nov-11 17:45pm

1 solution

Rate this: bad
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.


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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.170915.1 | Last Updated 22 Nov 2011
Copyright © CodeProject, 1999-2017
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