2010-01-30 63 views
1

空處理用於轉換LINQ到數據表中,我使用下面的擴展方法(來自#2兩者)在中WriteXML

LINQ到數據表

public static DataTable ToDataTable<T>(this IEnumerable<T> items) 
{ 
     DataTable table = new DataTable(typeof(T).Name); 
     PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | 
                BindingFlags.Instance); 
     foreach (var prop in props) 
     { 
      Type propType = prop.PropertyType; 
      // Is it a nullable type? Get the underlying type 
      if (propType.IsGenericType && 
       propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
       propType = new NullableConverter(propType).UnderlyingType; 
       table.Columns.Add(prop.Name, propType); 
      } 

      foreach (var item in items) 
      { 
       var values = new object[props.Length]; 
       for (var i = 0; i < props.Length; i++) 
         values[i] = props[i].GetValue(item, null); 
       table.Rows.Add(values); 
      } 
      return table; 
     } 

中WriteXML

PersonDB.PersonDataContext con = new PersonDB.PersonDataContext(); 
    DataTable tb = new DataTable(); 
    tb = con.Persons.ToDataTable(); 
    tb.WriteXml(@"d:\temp\Person.xml"); 

Que Stion的


的擴展方法創建的XML文件,但對於空值沒有元素在XML文件中創建。它說,如果委員會領域是空的,那麼委託元素在Xml代中缺失。

我想爲空值(ref類型)插入帶空字符串的元素,用小數和(0)插入整數。我需要做哪些改變?

回答

1

我將創建數據表的擴展方法,它確實是:

public static DataTable ZeroNullValues(this DataTable dataTable) 
{ 
    foreach(DataRow row in dataTable.Rows) 
    { 
     for(int i=0;i<dataTable.Columns.Count;i++) 
     { 
      if(row[i] == null) 
      { 
       Type columnType = dataTable.Columns[i].DataType; 
       if(columnType == typeof(string)) 
       { 
        row[i] = string.Empty; 
       } 
       else if(columnType == typeof(int) || columnType == typeof(long)) 
       { 
        row[i] = 0; 
       } 
       else if(columnType == typeof(float) || columnType == typeof(double)) 
       { 
        row[i] = 0.00F; 
       } 
      } 
     } 
    } 
    return dataTable; 
} 
0

正如我前面已經回答here

您可以使用WriteXmlSchema(和ReadXmlSchema)來存儲表的架構。這將意味着雖然XML列中不包含NULL列,但它們仍然可以正確導入。

using (SqlCommand sqlCommand = new SqlCommand(QUERY, CONNECTION)) 
{ 
    SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand); 
    DataSet dataSet = new DataSet(); 
    dataAdapter.Fill(dataSet); 
    dataSet.WriteXmlSchema(@"C:\TEMP\Schema.xsd"); 
    dataSet.Tables[0].WriteXml(@"C:\TEMP\Output.xml"); 
} 

有上有一個真正有用的文章在這裏:Save Dataset to XML With Null Values

相關問題