C#实现Class转DataTable并反序列化指定XML字符串的技术问询
Alright, let's tackle your problem step by step. We'll first map your XML structure to C# classes, handle the deserialization, then convert the deserialized objects into a DataTable. Here's how to do it:
1. Define C# Classes Matching the XML Structure
First, we need to create classes that mirror your XML hierarchy. We'll use System.Xml.Serialization attributes to ensure proper mapping between XML elements and class properties:
using System.Collections.Generic; using System.Xml.Serialization; [XmlRoot("cls_Yeni_Goc_Tespit_Formu")] public class ClsYeniGocTespitFormu { [XmlElement("hastaBilgileri")] public List<HastaBilgileri> HastaBilgileriList { get; set; } = new List<HastaBilgileri>(); } public class HastaBilgileri { public string TC { get; set; } public string AdSoyad { get; set; } public string DogumTarihi { get; set; } public string Ozellik { get; set; } public string GocAdres { get; set; } public string Gsm { get; set; } }
2. Implement XML Deserialization
Next, we'll write a helper method to deserialize your XML string into the ClsYeniGocTespitFormu object. This uses the built-in XmlSerializer to handle the conversion:
using System.IO; using System.Xml.Serialization; public static ClsYeniGocTespitFormu DeserializeXml(string xmlString) { var serializer = new XmlSerializer(typeof(ClsYeniGocTespitFormu)); using var reader = new StringReader(xmlString); return (ClsYeniGocTespitFormu)serializer.Deserialize(reader); }
3. Convert Deserialized Classes to DataTable
Now, let's create a generic method to convert a list of objects into a DataTable. This works for any class type, including our HastaBilgileri class, and handles null values properly:
using System.Data; using System.Reflection; public static DataTable ConvertListToDataTable<T>(List<T> items) { DataTable dataTable = new DataTable(typeof(T).Name); // Get all public instance properties of the class PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); // Add columns to the DataTable based on class properties foreach (PropertyInfo prop in props) { dataTable.Columns.Add(prop.Name, prop.PropertyType); } // Populate rows with data from the object list foreach (T item in items) { DataRow row = dataTable.NewRow(); foreach (PropertyInfo prop in props) { row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; } dataTable.Rows.Add(row); } return dataTable; }
4. Full Example Usage
Putting it all together, here's how you'd use these methods with your XML string:
using System; public static void Main() { // Your XML content (note: replace < with actual < in your code) string xml = @"<cls_Yeni_Goc_Tespit_Formu> <hastaBilgileri> <TC>12430104982</TC> <AdSoyad>AYŞE BERİL HARMANLI</AdSoyad> <DogumTarihi>20.09.1989</DogumTarihi> <Ozellik>Gebe Izlem 27.03.2018 I. Izlem</Ozellik> <GocAdres /> <Gsm>03121235689</Gsm> </hastaBilgileri> <hastaBilgileri> <TC>12433104828</TC> <AdSoyad>İPEK HARMANLI</AdSoyad> <DogumTarihi>20.09.1989</DogumTarihi> <Ozellik>Routine Checkup</Ozellik> <GocAdres>Ankara, Türkiye</GocAdres> <Gsm>03129876543</Gsm> </hastaBilgileri> </cls_Yeni_Goc_Tespit_Formu>"; // Step 1: Deserialize XML to C# class var formData = DeserializeXml(xml); // Step 2: Convert the list of hastaBilgileri to DataTable DataTable hastaTable = ConvertListToDataTable(formData.HastaBilgileriList); // Optional: Verify the DataTable output Console.WriteLine("DataTable Columns:"); foreach (DataColumn col in hastaTable.Columns) { Console.Write($"{col.ColumnName}\t"); } Console.WriteLine("\n\nDataTable Rows:"); foreach (DataRow row in hastaTable.Rows) { foreach (var item in row.ItemArray) { Console.Write($"{(item == DBNull.Value ? "N/A" : item.ToString())}\t"); } Console.WriteLine(); } }
Quick Notes:
- Ensure your project references
System.Xml,System.Data, andSystem.Reflectionassemblies. - If you need to parse
DogumTarihiinto aDateTimetype, modify theHastaBilgileriproperty toDateTimeand add[XmlElement(DataType = "date")](or handle manual parsing after deserialization). - The
ConvertListToDataTablemethod replaces null values withDBNull.Valueto maintain DataTable compatibility.
内容的提问来源于stack exchange,提问作者Aranel

