Determine if a XmlNode is empty or null in C#?

Michael Kniskern picture Michael Kniskern · Jan 25, 2011 · Viewed 7.9k times · Source

The following code takes an XmlNode data type and populates a DataSet object with the XmlNode content. Then I write the dataset's content to file.

public void PopulateDataSet(XmlNode node)
{
    XmlNodeReader reader = new XmlNodeReader(node);
    DataSet ds = new DataSet();
    ds.ReadXml(reader);

    system.Guid guid = System.Guid.NewGuid();
    string name = string.Format("{0}{1}_{2}.xml", Utility.XmlOutputPath, Utility.XmlOutputFileName, guid.ToString());

    //need to write "Node empty" to file if XmlNode object is empty of null
    ds.WriteXml(name, XmlWriteMode.IgnoreSchema);
}

The problem is that I encountered one scenario that it will not write the content to file. How do I determine if a XmlNode object is null or empty?

Answer

Davide Piras picture Davide Piras · Jan 25, 2011

You can check if the node parameter is null or has InnerText or InnerXml properties are null or empty, immediately when you enter the method before even creating the XmlNodeReader.