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

0

1 Answer 1

-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
}
Sign up to request clarification or add additional context in comments.

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.