Skip to main content

Converts entire DataTable to XDocument.

//
// Converts entire DataTabel To XDocument
public static XDocument ToXml(this DataTable dt, string rootName)
{
    var xdoc = new XDocument
    {
        Declaration = new XDeclaration("1.0", "utf-8", "")
    };

    xdoc.Add(new XElement(rootName));
        foreach (DataRow row in dt.Rows)
        {
            var element = new XElement(dt.TableName);
            foreach (DataColumn col in dt.Columns)
            {
                element.Add(new XElement(col.ColumnName, row[col].ToString().Trim(' ')));
            }
            if (xdoc.Root != null) xdoc.Root.Add(element);
        }

    return xdoc;
}

//
// Example
dtCert.ToXml("Certs");