在WriteXml中处理Null

时间:2010-01-30 22:33:46

标签: asp.net xml linq reflection datatable

为了将Linq转换为DataTable,我使用以下扩展方法(取自Stackoverflow)

Linq to DataTable

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");

问题


扩展方法创建XML文件,但对于空值,不会在XML文件中创建任何元素。它说如果Commission字段为null,则在Xml生成中缺少委托元素。

我想插入带空字符串的元素,用于空值(ref类型)和(0.00)表示小数,(0)表示整数。我需要在哪里进行更改?

2 个答案:

答案 0 :(得分:2)

我会为DataTable创建一个扩展方法:

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;
}

答案 1 :(得分: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