Azad Chouhan
Azad Chouhan

Reputation: 275

How to check if xml file is empty or not using c#

Hello everyone I want to check my xml file if it is empty or not. I am trying to update one xml data to another for this I am using the following code.Now Please tell me how can I check if my xml file has data or not Here is the code I am using for update my xml file

protected void CheckUpdates()
{
    StringReader strReader = new StringReader("..\\xml\\Updatelist.xml");
    XmlReader reader = XmlReader.Create(strReader);
    try
    {
       while (reader.Read())
       {
           var originalXmlDoc = XDocument.Load("..\\xml\\list.xml"); var newXmlDoc = XDocument.Load("..\\xml\\Updatelist.xml");

           foreach (var newElement in newXmlDoc.Element("blocker").Elements("lst"))
           {
               newElement.Value.Trim();
               if (!originalXmlDoc.Element("blocker").Elements("lst")
                       .Any(oldElement => oldElement.Value.Trim().Equals(
                       newElement.Value.Trim(),
                       StringComparison.InvariantCultureIgnoreCase)))
                {
                   originalXmlDoc.Element("blocker").Add(new XElement("lst", newElement.Value));
                }
             }
             originalXmlDoc.Save("..\\xml\\list.xml", SaveOptions.None);

             XmlDocument doc = new XmlDocument();
             doc.Load("..\\xml\\Updatelist.xml");
             doc.DocumentElement.RemoveAll();
             doc.Save("..\\xml\\Updatelist.xml");
          }
       }
    catch (XmlException ex)
    {
       //Catch xml exception
       //in your case: root element is missing
    }
}

I am Getting this error

Data at the root level is invalid. Line 1, position 1.

Please tell me how can I check if my Updatelist.xml is empty or not?

Now I get this error

Upvotes: 5

Views: 28671

Answers (3)

user23168774
user23168774

Reputation: 1

Additionally, XmlNode has a property that can be checked:

public virtual bool HasChildNodes { get; }

https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlnode.haschildnodes?view=net-8.0

Upvotes: 0

Pantelis Natsiavas
Pantelis Natsiavas

Reputation: 5369

Two ways to do it.

The first is to read the file and check its structure in order to see if there are any children in it. Keep in mind that the property ChildNodes returns only the children on the specific level of the XML DOM.

XmlDocument xDoc = new XmlDocument();
if (xDoc.ChildNodes.Count == 0) { 
    // It is empty 
}else if (xDoc.ChildNodes.Count == 1) { 
    // There is only one child, probably the declaration node at the beginning
}else if (xDoc.ChildNodes.Count > 1) { 
    // There are more children on the **root level** of the DOM
}

The second way would be to catch the respective XMLException thrown when the document is loaded.

try
{
    XmlDocument doc = new XmlDocument();
    doc.Load("test.xml");
}
catch (XmlException exc)
{
    //invalid file
}

Hope I helped!

Upvotes: 12

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

You can try to load the XML into XML document and catch the exception. Here is the sample code:

var doc = new XmlDocument();
try {
  doc.LoadXml(content);
} catch (XmlException e) {
  // put code here that should be executed when the XML is not valid.
}

Hope it helps.

(Or)

If you want the function (for stylistic reasons, not for performance), implement it yourself:

public class MyXmlDocument: XmlDocument
{
  bool TryParseXml(string xml){
    try{
      ParseXml(xml);
      return true;
    }catch(XmlException e){
      return false;
    }
 }

Use this function to know whether it is valid or not

Source

Upvotes: 1

Related Questions