使用LINQ将数据表转换为XML [英] Datatable to XML using LINQ

查看:229
本文介绍了使用LINQ将数据表转换为XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一种使用LINQ转换数据表的方法.我能够将数据表直接转换为XML,如下所示:

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

但是我需要一些帮助来编写一个方法,该方法将具有任意列数的数据表作为输入并将这样的内容写入xml:这个lamdba表达式不起作用,但是我正在寻找一种简化方法.预先感谢您的帮助

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

推荐答案

您正在寻找

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

这篇关于使用LINQ将数据表转换为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆