简体   繁体   English

使用Linq C#为DataTable的每个记录创建XML文件

[英]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. 目前,我正在使用来自单个XML文件中数据表的所有记录创建XML文件,我想使用linq分别为每个记录创建XML文件。

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

You can create xml for each row by using ForEach method 您可以使用ForEach方法为每一row创建xml

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM