2013-12-09 128 views
0

我有一個類和一個來自數據庫的查詢,填充DataSet中的DataTable。被序列化Datatable來填充(Object)標記。Serilize DataTable(Dataset)to Object

對象:

public class Marks 
    { 
     /// <summary> 
     /// 
     /// </summary> 
     public List<Mark> MarkList { get; set; } 

     public Marks() 
     { 
      MarkList = new List<Mark>(); 
     } 
    } 


    public class Mark 
    { 
     public String Number { get; set; } 

     public String Word { get; set; } 

     public DateTime? DateIn { get; set; } 

     public DateTime? DateOut { get; set; } 
    } 

我試着這樣做:

private void BindMarksSerialize() 
{  
    FillDataTable(dtMarks, MarksCMD); 

    MemoryStream stream = new MemoryStream(); 
    dtMarks.WriteXml(stream); 
    XmlSerializer serializer = new XmlSerializer(typeof(Marks), new XmlRootAttribute("Marks")); 
    File.WriteAllBytes("C:\\Out.xml", stream.ToArray()); 


    StreamReader reader = new StreamReader("C:\\Out.xml"); 
    var marks = (Marks)serializer.Deserialize(reader); 
    reader.Close(); 
} 

private void FillDataTable(DataTable dataTable, Object sqlCommandContainer) 
{ 
    var sqlCommand = sqlCommandContainer as SqlCommand; 
    var sqlDataAdapter = sqlCommandContainer as SqlDataAdapter; 
    if (sqlDataAdapter == null && sqlCommand == null) 
     return; 
    try 
    { 
     dataTable.Clear(); 
     if (sqlCommand != null) 
     { 
      sqlCommand.Connection.Open(); 
      dataTable.Load(sqlCommand.ExecuteReader()); 
     } 
     else 
      sqlDataAdapter.Fill(dataTable); 
    } 
    catch (SqlException ex) 
    { 
     Logger.Error(new StackTrace(1).GetFrame(0).GetMethod().Name + @": " + Environment.NewLine + ex.Message); 
    } 
    finally 
    { 
     if (sqlCommand != null) 
      sqlCommand.Connection.Close(); 
    } 
} 

需要結果來填充XML:

<Marks xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <MarkList> 
    <Mark> 
     <Number>1</Number> 
     <Word>123123123</Word> 
     <DateIn xsi:nil="true" /> 
     <DateOut xsi:nil="true" />  
    </Mark> 
    </MarkList> 
</Marks> 

我:

<NewDataSet> 
    <Mark> 
    <Number>110938</Number> 
    <Word>110938</Word> 
    <DateIn>1993-04-08T00:00:00+05:00</DateIn> 
    <DateOut>2002-02-04T00:00:00+04:00</DateOut>  
    </Mark> 
</NewDataSet> 

提示任何人都可以知道如何做到這一點?

回答

1

如果我正確地理解了您的問題,您將DataSet寫入XML文件時遇到問題,但將標記類類型對象的列表寫入XML時沒有問題。

您可以使用反射來創建一個可重用的函數,它將從任何Datatable中讀取Datarow並將其分配給您作爲參數傳遞的任何對象。如果您想要該對象的List,那麼您可以遍歷DataTable的DataRows。在下面的示例中,我從單行生成一個對象。 (這是一種可重複使用的映射。)

public static object ConvertDataRowToObject(object Object, DataTable DataTable) 
{ 
    try 
    { 
     if (DataTable.Rows.Count > 0) 
     { 
      DataRow DataRow = DataTable.AsEnumerable().FirstOrDefault(); 
      if (DataRow != null) 
      { 
       Type ObjectType = Object.GetType(); 
       //Get public properties 
       System.Reflection.PropertyInfo[] _propertyInfo = 
        ObjectType.GetProperties(); 
       foreach (System.Reflection.PropertyInfo _property in _propertyInfo) 
       { 
        _property.SetValue(Object, (DataRow[_property.Name.ToString()] is System.DBNull ? null : DataRow[_property.Name.ToString()]), null); 
       } 
       return Object; 
      } 
      else return null; 
     } 
     else 
      return null; 
    } 
    catch (Exception excp) 
    { 
     Common.WriteErrorLog(excp.Message); 
     return null; 
    } 
} 

現在,當我需要調用此靜態重用的功能,我可以做這樣的樣品。

Database _dbFactory = Common.Database; 
       DataSet dset = new DataSet(); 
       Object[] _dbObject = DataBaseHelper.CreateConnection(); 
       dset = _dbFactory.ExecuteDataSet("Jwl_sp_SearchByProductCategoryById", new object[] { _Id }); 
       DataBaseHelper.CloseConnection((SqlConnection)_dbObject[0]); 
       DataTable dt = new DataTable(); 
       dt = dset.Tables[0]; 
       var objectTobeConverted = new DataLogic.Database.Jwl_ByProductCategory(); 
       ConvertDataRowToObject(objectTobeConverted, dt); 

我使用Javascript序列化器對這個對象進行了序列化。下一步你的情況是寫入一個xml文檔,你可以使用xmlSerialization,或者我會建議使用XMLWriter。

public static string GetJSONSerializedObject(object myItem) 
{ 
    try 
    { 
     if (myItem != null) 
     { 
      List<KeyValuePair<string, string>> _propList = new List<KeyValuePair<string, string>>(); 

      Type myObjectType = myItem.GetType(); 
      //Get public properties 
      System.Reflection.PropertyInfo[] _propertyInfo = 
       myObjectType.GetProperties(); 
      foreach (System.Reflection.PropertyInfo _property in _propertyInfo) 
      { 
       string _key = String.Empty; 
       string _value = String.Empty; 
       _key = _property.Name.ToString(); 
       _value = (_property.GetValue(myItem, null) != null) ? Convert.ToString(_property.GetValue(myItem, null)) : ""; 
       _propList.Add(new KeyValuePair<string, string>(_key, _value)); 
      } 
      if (_propList.Count > 0) 
      {// Serializing an object's properties 
       System.Web.Script.Serialization.JavaScriptSerializer jsSerializer; 
       jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
       System.Text.StringBuilder _strBuild = new System.Text.StringBuilder(); 
       jsSerializer.Serialize(_propList, _strBuild); 
       return _strBuild.ToString(); 


      } 
      else { return null; } 
     } 
     else { return null; } 
    } 
    catch (Exception excp) 
    { 
     Common.WriteErrorLog(excp.Message); 
     return null; 
    } 
} 
+0

我認爲OP在編寫CORRECT xml時遇到了麻煩。注意最後兩段。一個是「這是我想要的」,另一個是「這就是我得到的」 – paqogomez