使用LINQ将数据转换为XML

时间:2012-02-07 23:26:03

标签: c# linq-to-xml

我正在编写一个使用LINQ转换数据表的方法。我可以直接从datatable转换为XML,如下所示:

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表达式不起作用,但我正在寻找一种方法来简化它。在此先感谢您的帮助

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

2 个答案:

答案 0 :(得分:3)

试试这个

XElement container = new XElement("container");

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

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

答案 1 :(得分:2)

您正在寻找

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