[技術] 將DataTable轉換成XML格式 (Convert DataTable to XML)

[技術] 將DataTable轉換成XML格式 (Converting DataTable to XML)

# 使用WriteXml方法

   1: XElement tElement = new XElement("tTable", "");
   2:     using (XmlWriter tWriter = tElement.CreateWriter())
   3:     {
   4:         tTable.WriteXml(tWriter, XmlWriteMode.IgnoreSchema, false);
   5:         //pDataTable.WriteXml(tWriter, XmlWriteMode.IgnoreSchema, false);
   6:     }
   7:     XElement tElement2 = new XElement("DataTable", tElement.Element("DocumentElement").Elements()); 

 

要注意的是,若使用WriteXml方法,當DataTable有欄位為Null時,它便不會把那個欄位組成XML tag。

若想要每個欄位都組成XML tag,便要用迴圈的方式將欄位一個一個組成tag。

   1: private XElement DataTableToXml(DataTable pAttributeTable, string tParentTag)
   2: {
   3:     if (pAttributeTable == null)
   4:     {
   5:         return null;
   6:     }
   7:  
   8:     XElement tParent = null;
   9:     try
  10:     {
  11:         tParent = new XElement(tParentTag);  // 集合Tag的名字
  12:  
  13:         //每個DataRow為屬性分類
  14:         foreach (DataRow tRow in pAttributeTable.Rows)
  15:         {
  16:             XElement tChild = new XElement("DataRow");
  17:             //每個DataRow的DataColumn為屬性分類裡的項目
  18:             foreach (DataColumn tColumn in pAttributeTable.Columns)
  19:             {
  20:                 tChild.Add(new XElement(tColumn.ColumnName, tRow[tColumn]));
  21:             }
  22:             tParent.Add(tChild);
  23:         }
  24:        
  25:     }
  26:  
  27:     catch (Exception ex)
  28:     {
  29:         throw ex;
  30:     }
  31:     return tParent;
  32: }