C#实现List与XML数据互换的简单类型支持

4星 · 超过85%的资源 需积分: 50 95 下载量 147 浏览量 更新于2024-09-12 1 收藏 7KB TXT 举报
本文主要介绍如何在C#中实现List对象与XML字符串之间的相互转换,特别支持简单数据类型如int、long、datetime、string、double、decimal以及object。 在C#编程中,有时我们需要将数据结构(如List)转换成XML格式以便存储或传输,或者从接收到的XML字符串中还原回数据结构。以下方法提供了一个方便的解决方案,特别是对于那些只包含基本类型数据的列表。 首先,我们来看一下如何将一个List对象转换为XML字符串。这个过程通常涉及到遍历列表中的每个元素,并将其转换为XML节点。下面的方法定义了一个泛型函数,它接受一个类型T作为参数,这个类型应该是上述支持的简单类型之一: ```csharp public static string ListToXml<T>(List<T> list) { if (list == null || list.Count == 0) { return string.Empty; } Type tp = typeof(T); if (!(tp == typeof(string) || tp == typeof(int) || tp == typeof(long) || tp == typeof(DateTime) || tp == typeof(double) || tp == typeof(decimal))) { throw new ArgumentException("Unsupported type."); } StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.Append("<root>"); foreach (T item in list) { xmlBuilder.Append("<item>"); xmlBuilder.Append(item.ToString()); xmlBuilder.Append("</item>"); } xmlBuilder.Append("</root>"); return xmlBuilder.ToString(); } ``` 这个方法首先检查传入的类型是否为支持的类型,然后遍历列表,将每个元素的ToString()结果封装到XML节点中。最后,所有节点都被包裹在`<root>`标签内,形成一个完整的XML字符串。 接下来,我们将XML字符串转换回List对象。同样,这里有一个泛型方法`xmlToList<T>`,它接受一个XML字符串作为输入: ```csharp public static List<T> XmlToList<T>(string xml) { Type tp = typeof(T); List<T> list = new List<T>(); if (xml == null || string.IsNullOrEmpty(xml)) { return list; } try { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); if (tp == typeof(string) || tp == typeof(int) || tp == typeof(long) || tp == typeof(DateTime) || tp == typeof(double) || tp == typeof(decimal)) { XmlNodeList nl = doc.SelectNodes("/root/item"); if (nl.Count == 0) { return list; } else { foreach (XmlNode node in nl) { if (tp == typeof(string)) { list.Add((T)(object)Convert.ToString(node.InnerText)); } else if (tp == typeof(int)) { list.Add((T)(object)Convert.ToInt32(node.InnerText)); } else if (tp == typeof(long)) { list.Add((T)(object)Convert.ToInt64(node.InnerText)); } else if (tp == typeof(DateTime)) { list.Add((T)(object)Convert.ToDateTime(node.InnerText)); } else if (tp == typeof(double)) { list.Add((T)(object)Convert.ToDouble(node.InnerText)); } else if (tp == typeof(decimal)) { list.Add((T)(object)Convert.ToDecimal(node.InnerText)); } } } } else { throw new ArgumentException("Unsupported type."); } } catch (Exception ex) { // 处理加载XML时可能抛出的异常 } return list; } ``` 这个方法首先加载XML字符串到一个XmlDocument对象,然后遍历`<root>`下的所有`<item>`节点,根据类型T将节点的文本内容转换为相应的简单类型,并添加到返回的List中。 通过这两个方法,我们可以方便地在C#中实现List对象与XML字符串之间的互转,适用于处理包含简单类型数据的列表。需要注意的是,这些方法并不适用于复杂的对象序列化,如果需要序列化具有复杂结构的对象,可以考虑使用.NET框架提供的XmlSerializer类或其他第三方库。