Create an XML from a DataTable

后端 未结 3 1590
离开以前
离开以前 2020-12-16 04:30

\"DataTable

Using C# : I want to convert this table into XML. Please ignore

相关标签:
3条回答
  • 2020-12-16 05:07
    public static string ToXml(this DataTable table, int metaIndex = 0)
    {
        XDocument xdoc = new XDocument(
            new XElement(table.TableName,
                from column in table.Columns.Cast<DataColumn>()
                where column != table.Columns[metaIndex]
                select new XElement(column.ColumnName,
                    from row in table.AsEnumerable()
                    select new XElement(row.Field<string>(metaIndex), row[column])
                    )
                )
            );
    
        return xdoc.ToString();
    }
    

    This worked great for me. Thanks stackoverflow.

    0 讨论(0)
  • 2020-12-16 05:09

    DataTables are designed to iterate over rows, not columns like you have. There's nothing built-in to persist a DataTable in column-major order. You're going to have use custom code. Pseudo-code would be something like:

    foeeach(DataColumn)
      if(name != "Name")
        output column header
        foreach(DataRow) 
          output row value
    
    0 讨论(0)
  • 2020-12-16 05:23

    you can try using this

    http://msdn.microsoft.com/en-us/library/system.data.datatable.writexml.aspx

    DataTable youdatatable = GetData();
    System.IO.StringWriter writer = new System.IO.StringWriter();
     youdatatable.WriteXml(writer, XmlWriteMode.WriteSchema, true);
     PrintOutput(writer);
    
    0 讨论(0)
提交回复
热议问题