Datatable to XML using LINQ

雨燕双飞 提交于 2019-12-24 10:58:30

问题


I am writing a method to convert datatable using LINQ. I was able to get straight forward conversion from datatable to XML as below:

XDocument doc = new XDocument(new XDeclaration("1.0","UTF-8","yes"),
   new XElement("pfolios", from p in dt.AsEnumerable()
    select new XElement("pfolio",
        new XAttribute("ID", p.ID), 
        new XAttribute("Date", p.Date),
        new XAttribute("Expired", p.Expiry))));

but I need some help to write a method, that takes datatable with any number of columns as input and write to xml something like this: This lamdba expression does not work but I am looking for a way to simplify this. Thanks in advance for your help

  XElement xe = new XElement("pfolios", from p in dt.AsEnumerable()
             select new XElement("pfolio",dt.AsEnumerable().ToList().ForEach(dc=> dt.Columns) 
new XAttribute(dc.ColumnName, p[dc.ColumnName])));

回答1:


You're looking for

table.AsEumerable().Select(row =>
    new XElement("row",
        table.Columns.Cast<DataColumn>().Select(col =>
            new XAttribute(col.ColumnName, row[col])
        )
    )
)



回答2:


Try this

XElement container = new XElement("container");

using (XmlWriter w = container.CreateWriter()) {

  DataTable.WriteXml(w, System.Data.XmlWriteMode.WriteSchema, true);
 }


来源:https://stackoverflow.com/questions/9185654/datatable-to-xml-using-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!