1

I want to handle the empty file which does not contain any data after running below code it gives error like root element is missing.

How can I check xDoc is null or empty?

string path = @"E:\Test.xml";
XDocument xDoc = XDocument.Load(path);
Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
yash fale
  • 235
  • 1
  • 4
  • 19
  • 2
    Try this: http://stackoverflow.com/questions/375590/how-does-one-test-a-file-to-see-if-its-a-valid-xml-file-before-loading-it-with – YuvShap Oct 17 '16 at 11:49
  • path is already exist but file is empty , i can use try catch but need some other method to check particular XDocument is null or empty – yash fale Oct 17 '16 at 11:55
  • It didn't understand why the try catch block does not answer your problem, can you explain what the result you want? – YuvShap Oct 17 '16 at 11:59
  • i just want to avoid this error , for string we can simply check like string.IsNullOrEmpty() why we cant able to check for any XmlDoxument or XDocument – yash fale Oct 17 '16 at 12:03
  • @yashfale because this is not string... – mybirthname Oct 17 '16 at 12:05
  • Just set xDoc to null in the catch block, and then check that the doc is not null before you use it elsewhere in your code (if(xDoc != null)). – YuvShap Oct 17 '16 at 12:06

1 Answers1

1

XDocument.Load expects a valid XML file. Otherwise an exception will be thrown. You can either check, if the file exists or is empty before calling XDocument.Load , e.g. via

if (new System.IO.FileInfo(path).Length > 0)
{
   ...
}

or you can catch the exception.

string path = @"E:\Test.xml";
try
{
    XDocument xDoc = XDocument.Load(path);
} catch(Exception) {
   // some problem
}

If this code is put into a static function the code would be more readable.

 var xDoc = MyXDocument.Load(path);
 if (xDoc != null)
 { .... 
 }

public class MyXDocument {
    public static XDocument Load(string path) {
        try
        {
             XDocument xDoc = XDocument.Load(path);
             return xDoc;
        } catch(Exception) {
            return null;
        }
    }
}
Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
  • i can handle like this but need some other method in which i can able check the XDocument is null or empty – yash fale Oct 17 '16 at 11:56
  • @yashfale - can you elaborate more in your question, why these kind of checks do not match your requirements ? If it is a matter of style you can write a static helper method like MyXDocument.Load() that returns null, if some error happened during loading. – Ralf Bönning Oct 17 '16 at 12:00
  • understood ! , we have to use try catch block. no other way to check null or empty for XDocument . Thanks. – yash fale Oct 17 '16 at 12:17