0

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

1 Answer 1

3

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");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.