ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToXml

Converts entire DataTabel To XDocument

Source

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")

Author: Meysam Javadi

Submitted on: 31 okt. 2012

Language: C#

Type: System.Data.DataTable

Views: 8542