Search code examples
c#xmldatatable

How do I build a function that transforms the columns entered from the DataTable to xml?


There is no problem in converting static columns to xml The problem is that I'm trying to make the conversion through an array and insert it as I need it every time can you add loop to XElement

  string  creatColumnXml(params int[] ColId)
        {
            
            return new XElement(table.TableName, table.Rows.Cast<DataRow>().Select(row =>
                 new XElement("row",
                         //for ( int i =0;i<ColId.Length;i++)
                         //new XElement(table.Columns[ColId[i]].ColumnName, row[ColId[i]]),
                         new XElement(table.Columns[0].ColumnName, row[0]),
                         new XElement(table.Columns[1].ColumnName, row[1]),
                          new XElement(table.Columns[2].ColumnName, row[2])

                 ))
            ).ToString();
        }

Solution

  • You can use LINQ again within your existing lambda

    string creatColumnXml(params int[] ColId)
    {
        return new XElement(table.TableName,
            table.Rows.Cast<DataRow>().Select(row =>
                new XElement("row",
                    ColId.Select(c => new XElement(table.Columns[c].ColumnName, row[c]))
                )
            ).ToString();
    }