2

I am trying to loop through a directory to search all xml files. I got this accomplish by doing Directory.EnumerateFiles and by finding every .xml type. The thing is now, there are some random xml files that are empty with no information written in them. I want to check for all files that do not have any information in them.

Code

foreach (string file in Directory.EnumerateFiles("/xmlFiles", "*.xml", SearchOption.AllDirectories))
{
    //Find the XML File
    XDocument doc = XDocument.Load(file);

    //Check if the XDocument doc has no root element 
    if (doc == null)
    {
        Console.WriteLine(File + " has NO root element");
    }
    else
    {
        Console.WriteLine(File + " has a root element");
    }
}

I tried doing a if else statement comparing the file to null after parsing the xml file but I get a error when loading my file before I can compare it.

Error: System.Xml.XmlException: 'Root element is missing.'

carlos E.
  • 115
  • 2
  • 11

1 Answers1

-1

Could always do a try catch to see if it's empty. Dup question How to check if xml file is empty or not using c#

   try
{
    XmlDocument doc = new XmlDocument();
    doc.Load("some.xml");
}
catch (XmlException exc)
{
    //invalid file
}
Bob
  • 43
  • 1
  • 1
  • 7
  • So I got the try catch function to work but it ends my script once it finds an error. How would I modify the try catch function where it would still continue the script and give me like a Console line error when a file is empty? – carlos E. Dec 21 '17 at 16:46
  • I guess it comes down to what you're trying to get out of it. If you're just trying to skip the file you could do like a method that either returns the xml doc loaded if it's a proper or return null if there was an exception. @carlosE. – Bob Dec 21 '17 at 18:23