yash fale
yash fale

Reputation: 331

create XML file for each record of the DataTable using Linq C#

Currently i am creating XML file from all the records coming from Data Table in single XML file , i want to create XML file for each record separately using linq.

DataTable dtTest = new DataTable();
dtTest.Columns.Add("Name");
dtTest.Columns.Add("NickName");
dtTest.Columns.Add("Code");
dtTest.Columns.Add("reference");

dtTest.Rows.Add("Yash", "POPs", "Vapi", "None1");
dtTest.Rows.Add("shilpa", "shilpa", "valsad", "None2");
dtTest.Rows.Add("Dinesh", "dinu", "pune", "None3");
dtTest.Rows.Add("rahul", "mady", "pardi", "None4");

XDocument xmlDoc = new XDocument(
    new XElement(
        "File",
        from fields in dtTest.AsEnumerable()
        select new XElement(
            "company_details",
            new XElement(
                "company",
                new XElement(
                    "Name",
                    fields.Field<string>("Name")),
                new XElement(
                    "NickName",
                    fields.Field<string>("NickName"))),
            new XElement(
                "Details",
                new XElement(
                    "reference",
                    fields.Field<string>("reference"))))));

string filepath = @"C:\Users\admin\Desktop\test.xml";
xmlDoc.Save(filepath);  

Upvotes: 0

Views: 1028

Answers (1)

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14624

You can create xml for each row by using ForEach method

DataTable dtTest = new DataTable();
dtTest.Columns.Add("Name");
dtTest.Columns.Add("NickName");
dtTest.Columns.Add("Code");
dtTest.Columns.Add("reference");

dtTest.Rows.Add("Yash", "POPs", "Vapi", "None1");
dtTest.Rows.Add("shilpa", "shilpa", "valsad", "None2");
dtTest.Rows.Add("Dinesh", "dinu", "pune", "None3");
dtTest.Rows.Add("rahul", "mady", "pardi", "None4");

dtTest.AsEnumerable().ToList().ForEach(x => CreateXml(x));

public void CreateXml(DataRow row)
{
  XDocument xmlDoc = new XDocument(
      new XElement(
          "File",
           new XElement(
               "company_details",
               new XElement(
                   "company",
               new XElement(
                   "Name",
                    row.Field<string>("Name")),
               new XElement(
                   "NickName",
                    row.Field<string>("NickName"))),
               new XElement(
                    "Details",
               new XElement(
                    "reference",
                     row.Field<string>("reference"))))));
  xmlDoc.Save(Server.MapPath(row.Field<string>("Name")) + ".xml");
}

Upvotes: 3

Related Questions