使用LINQ将数据表转换为XML
本文关键字:XML 转换 数据表 LINQ 使用 | 更新日期: 2023-09-27 18:23:35
我正在编写一个使用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])));
试试这个
XElement container = new XElement("container");
using (XmlWriter w = container.CreateWriter()) {
DataTable.WriteXml(w, System.Data.XmlWriteMode.WriteSchema, true);
}
您正在寻找
table.AsEumerable().Select(row =>
new XElement("row",
table.Columns.Cast<DataColumn>().Select(col =>
new XAttribute(col.ColumnName, row[col])
)
)
)