2012-02-07 43 views
1

我正在編寫一種使用LINQ轉換數據表的方法。我能夠從數據表中獲得直接的轉換爲XML如下:使用LINQ將數據錶轉換爲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

您正在尋找

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

這工作..非常感謝你!我想我需要回去磨練我的LINQ技能:)你可以建議任何好的書/網站? – user799891 2012-02-08 16:32:27

+0

http://linqpad.net – SLaks 2012-02-08 16:48:55

3

試試這個

XElement container = new XElement("container"); 

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

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