C# 如何编写转换列表的通用方法<;T>;转换为xml字符串
我从一个网站获得了一个例程C# 如何编写转换列表的通用方法<;T>;转换为xml字符串,c#,xml,generics,C#,Xml,Generics,我从一个网站获得了一个例程http://www.dotnetcurry.com/ShowArticle.aspx?ID=428 查看他们的代码 class Program { static void Main(string[] args) { List<Employee> empList = new List<Employee>(); empList.Add(new Employee(
http://www.dotnetcurry.com/ShowArticle.aspx?ID=428
查看他们的代码
class Program
{
static void Main(string[] args)
{
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { ID = 1, FName = "John", LName = "Shields", DOB = DateTime.Parse("12/11/1971"), Sex = 'M' });
empList.Add(new Employee() { ID = 2, FName = "Mary", LName = "Jacobs", DOB = DateTime.Parse("01/17/1961"), Sex = 'F' });
empList.Add(new Employee() { ID = 3, FName = "Amber", LName = "Agar", DOB = DateTime.Parse("12/23/1971"), Sex = 'M' });
empList.Add(new Employee() { ID = 4, FName = "Kathy", LName = "Berry", DOB = DateTime.Parse("11/15/1976"), Sex = 'F' });
empList.Add(new Employee() { ID = 5, FName = "Lena", LName = "Bilton", DOB = DateTime.Parse("05/11/1978"), Sex = 'F' });
}
}
class Employee
{
public int ID { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public DateTime DOB { get; set; }
public char Sex { get; set; }
}
正在寻求帮助。谢谢
编辑
我只是自定义了一点ToXml()
,但为什么会抛出错误呢?有什么想法吗
public static class utility
{
public static string ToXml<T>(this T obj, string strContainer = "")
{
XmlSerializer serialize = null;
if (strContainer.Trim() == "")
serializer = new XmlSerializer(typeof(T));
else
serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(strContainer));
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, obj);
return sw.ToString();
}
}
}
公共静态类实用程序
{
公共静态字符串ToXml(此T对象,字符串strContainer=“”)
{
XmlSerializer serialize=null;
if(strContainer.Trim()=“”)
serializer=新的XmlSerializer(typeof(T));
其他的
serializer=新的XmlSerializer(typeof(T),新的XmlRootAttribute(strContainer));
使用(StringWriter sw=new StringWriter())
{
序列化器。序列化(sw、obj);
返回sw.ToString();
}
}
}
查看是否可以使用此通用扩展
public static string ToXml<T>(this T obj)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, obj);
return sw.ToString();
}
}
使用您的代码生成此XML
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Employee>
<ID>1</ID>
<FName>John</FName>
<LName>Shields</LName>
<DOB>1971-12-11T00:00:00</DOB>
<Sex>77</Sex>
</Employee>
<Employee>
<ID>2</ID>
<FName>Mary</FName>
<LName>Jacobs</LName>
<DOB>1961-01-17T00:00:00</DOB>
<Sex>70</Sex>
</Employee>
</ArrayOfEmployee>
1.
约翰
盾牌
1971-12-11T00:00:00
77
2.
玛丽
雅各布斯
1961-01-17T00:00:00
70
编辑
要使用自定义根元素名称并删除名称空间,请使用此重载
public static string ToXml<T>(this T obj, string rootName)
{
XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));
var xmlNs = new XmlSerializerNamespaces();
xmlNs.Add(string.Empty, string.Empty);
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, obj, xmlNs);
return sw.ToString();
}
}
publicstaticstringtoxml(这个T对象,stringrootname)
{
XmlSerializer serializer=新的XmlSerializer(typeof(T),新的XmlRootAttribute(rootName));
var xmlNs=新的XmlSerializerNamespaces();
Add(string.Empty,string.Empty);
使用(StringWriter sw=new StringWriter())
{
serializer.Serialize(sw、obj、xmlNs);
返回sw.ToString();
}
}
产生
<?xml version="1.0" encoding="utf-16"?>
<Employees>
<Employee>
<ID>1</ID>
<FName>John</FName>
<LName>Shields</LName>
<DOB>1971-12-11T00:00:00</DOB>
<Sex>77</Sex>
</Employee>
<Employee>
<ID>2</ID>
<FName>Mary</FName>
<LName>Jacobs</LName>
<DOB>1961-01-17T00:00:00</DOB>
<Sex>70</Sex>
</Employee>
</Employees>
1.
约翰
盾牌
1971-12-11T00:00:00
77
2.
玛丽
雅各布斯
1961-01-17T00:00:00
70
您可以使用默认情况下可以序列化公共字段并可由自定义的。演示场景的最简单示例如下所示:
static void Main(string[] args)
{
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { ID = 1, FName = "John", LName = "Shields", DOB = DateTime.Parse("12/11/1971"), Sex = 'M' });
empList.Add(new Employee() { ID = 2, FName = "Mary", LName = "Jacobs", DOB = DateTime.Parse("01/12/1961"), Sex = 'F' });
empList.Add(new Employee() { ID = 3, FName = "Amber", LName = "Agar", DOB = DateTime.Parse("05/12/1971"), Sex = 'M' });
empList.Add(new Employee() { ID = 4, FName = "Kathy", LName = "Berry", DOB = DateTime.Parse("11/06/1976"), Sex = 'F' });
empList.Add(new Employee() { ID = 5, FName = "Lena", LName = "Bilton", DOB = DateTime.Parse("05/11/1978"), Sex = 'F' });
XmlSerializer serializer = new XmlSerializer(empList.GetType());
serializer.Serialize(Console.Out, empList);
Console.ReadKey();
}
static void Main(字符串[]args)
{
List empList=新列表();
Add(newemployee(){ID=1,FName=“John”,LName=“Shields”,DOB=DateTime.Parse(“12/11/1971”),Sex='M'});
Add(newemployee(){ID=2,FName=“Mary”,LName=“Jacobs”,DOB=DateTime.Parse(“01/12/1961”),Sex='F'});
Add(newemployee(){ID=3,FName=“Amber”,LName=“Agar”,DOB=DateTime.Parse(“05/12/1971”),Sex='M'});
Add(newemployee(){ID=4,FName=“Kathy”,LName=“Berry”,DOB=DateTime.Parse(“11/06/1976”),Sex='F'});
Add(newemployee(){ID=5,FName=“Lena”,LName=“Bilton”,DOB=DateTime.Parse(“05/11/1978”),Sex='F'});
XmlSerializer serializer=新的XmlSerializer(empList.GetType());
serializer.Serialize(Console.Out,empList);
Console.ReadKey();
}
此示例将显示下一个结果:
<?xml version="1.0" encoding="cp866"?>
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd
="http://www.w3.org/2001/XMLSchema">
<Employee>
<ID>1</ID>
<FName>John</FName>
<LName>Shields</LName>
<DOB>1971-11-12T00:00:00</DOB>
<Sex>77</Sex>
</Employee>
<Employee>
<ID>2</ID>
<FName>Mary</FName>
<LName>Jacobs</LName>
<DOB>1961-12-01T00:00:00</DOB>
<Sex>70</Sex>
</Employee>
<Employee>
<ID>3</ID>
<FName>Amber</FName>
<LName>Agar</LName>
<DOB>1971-12-05T00:00:00</DOB>
<Sex>77</Sex>
</Employee>
<Employee>
<ID>4</ID>
<FName>Kathy</FName>
<LName>Berry</LName>
<DOB>1976-06-11T00:00:00</DOB>
<Sex>70</Sex>
</Employee>
<Employee>
<ID>5</ID>
<FName>Lena</FName>
<LName>Bilton</LName>
<DOB>1978-11-05T00:00:00</DOB>
<Sex>70</Sex>
</Employee>
</ArrayOfEmployee>
1.
约翰
盾牌
1971-11-12T00:00:00
77
2.
玛丽
雅各布斯
1961-12-01T00:00:00
70
3.
琥珀色
琼脂
1971-12-05T00:00:00
77
4.
凯西
浆果
1976-06-11T00:00:00
70
5.
莉娜
比尔顿
1978-11-05T00:00:00
70
通用实现将更加简单,并且基于预期的结果类型。我正在使用以下代码:
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Rikrop.Core.Serialization.Xml
{
public static class XmlSerializers
{
private static readonly ConcurrentDictionary<Type, XmlSerializer> serializers = new ConcurrentDictionary<Type, XmlSerializer>();
private static readonly XmlSerializerNamespaces xns = new XmlSerializerNamespaces();
private static readonly UTF8Encoding defaultEncoding = new UTF8Encoding(false);
static XmlSerializers()
{
xns.Add("", "");
}
private static XmlSerializer GetSerializer(Type type, XmlRootAttribute xmlRoot = null)
{
return serializers.GetOrAdd(type, t => new XmlSerializer(t, xmlRoot));
}
public static byte[] SerializeToBytes<T>(T obj, bool omitXmlDeclaration = true, string customRootName = null, bool omitNamespaces = true, Encoding encoding = null)
{
if (ReferenceEquals(null, obj))
return null;
using (var ms = new MemoryStream())
{
var xmlSettings = new XmlWriterSettings
{
OmitXmlDeclaration = omitXmlDeclaration,
NewLineHandling = NewLineHandling.Entitize,
Indent = true,
Encoding = encoding ?? defaultEncoding
};
using (var xmlWriter = XmlWriter.Create(ms, xmlSettings))
{
var xmlRootNameAttribute = string.IsNullOrEmpty(customRootName) ? null : new XmlRootAttribute(customRootName);
GetSerializer(typeof(T), xmlRootNameAttribute).Serialize(xmlWriter, obj, omitNamespaces ? xns : null);
return ms.ToArray();
}
}
}
public static string Serialize<T>(T obj, bool omitNamespaces = true, Encoding encoding = null, bool omitXmlDeclaration = true, string customRootName = null)
{
var bytes = SerializeToBytes(obj, omitXmlDeclaration, customRootName, omitNamespaces, encoding);
return (encoding ?? defaultEncoding).GetString(bytes);
}
public static string SafeSerialize<T>(T obj, bool omitNamespaces = true, Encoding encoding = null, bool omitXmlDeclaration = true, string customRootName = null)
{
try
{
return Serialize(obj, omitNamespaces, encoding, omitXmlDeclaration, customRootName);
}
catch (Exception e)
{
// log error here
}
return null;
}
public static T SafeDeserialize<T>(byte[] serializedData, Encoding encoding = null, bool silentMode = false)
where T : class
{
try
{
return DeserializeFromBytes<T>(serializedData, encoding);
}
catch (Exception e)
{
if (!silentMode)
{
// log error here
}
}
return null;
}
public static T SafeDeserialize<T>(string serializedData, Encoding encoding = null, bool silentMode = false)
where T : class
{
try
{
return Deserialize<T>(serializedData, encoding);
}
catch (Exception e)
{
if (!silentMode)
{
// log error here
}
}
return null;
}
public static T DeserializeFromBytes<T>(byte[] serializedData, Encoding encoding = null) where T : class
{
using (var sr = new StreamReader(new MemoryStream(serializedData), encoding ?? defaultEncoding))
using (var xmlReader = XmlReader.Create(sr))
return (T) GetSerializer(typeof(T)).Deserialize(xmlReader);
}
public static T Deserialize<T>(string stringData, Encoding encoding = null) where T : class
{
var bytes = (encoding ?? defaultEncoding).GetBytes(stringData);
return DeserializeFromBytes<T>(bytes, encoding);
}
}
}
使用系统;
使用System.Collections.Concurrent;
使用System.IO;
使用系统文本;
使用System.Xml;
使用System.Xml.Serialization;
命名空间Rikrop.Core.Serialization.Xml
{
公共静态类XmlSerializer
{
私有静态只读ConcurrentDictionary序列化程序=新建ConcurrentDictionary();
私有静态只读XmlSerializerNamespaces xns=新XmlSerializerNamespaces();
私有静态只读UTF8Encoding defaultEncoding=新UTF8Encoding(false);
静态XmlSerializers()
{
添加(“,”);
}
私有静态XmlSerializer GetSerializer(类型类型,XmlRootAttribute xmlRoot=null)
{
返回serializers.GetOrAdd(type,t=>newxmlserializer(t,xmlRoot));
}
公共静态字节[]序列化为字节(T obj,bool-omitXmlDeclaration=true,string-customRootName=null,bool-omitNamespaces=true,Encoding-Encoding=null)
{
if(ReferenceEquals(null,obj))
返回null;
使用(var ms=new MemoryStream())
{
var xmlSettings=新的XmlWriterSettings
{
OmitXmlDeclaration=OmitXmlDeclaration,
NewLineHandling=NewLineHandling.Entitize,
缩进=真,
编码=编码??默认编码
};
使用(var xmlWriter=xmlWriter.Create(ms,xmlSettings))
{
var xmlRootNameAttribute=string.IsNullOrEmpty(customRootName)?null:新的XmlRootAttribute(customRootName);
GetSerializer(typeof(T),xmlRootNameAttribute).Serialize(xmlWriter,obj,省略名称空间?xns:null);
返回ToArray女士();
}
}
}
公共静态字符串序列化(T obj,bool ommitNamespaces=true,Encoding Encoding=null,bool ommitXMLDeclaration=true,string customRootName=null)
{
var bytes=SerializeToBytes(obj、omitXmlDeclaration、customRootName、omitNamespaces、encoding);
返回(编码??默认编码).GetString(字节);
}
公共静态字符串SafeSerialize(T obj,bool-omitnamespace=true,Encoding-Encoding=null,bool-omitxmldesclaration=true,string-customRootName=null)
{
尝试
{
返回序列化(obj、省略名称空间、编码、省略XmlDeclaration、customRootName);
}
捕获(例外e)
{
//此处记录错误
}
返回null;
}
public static T SafeDeserialize(字节[]serializedData,编码=null,bool silentMode=f
<?xml version="1.0" encoding="cp866"?>
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd
="http://www.w3.org/2001/XMLSchema">
<Employee>
<ID>1</ID>
<FName>John</FName>
<LName>Shields</LName>
<DOB>1971-11-12T00:00:00</DOB>
<Sex>77</Sex>
</Employee>
<Employee>
<ID>2</ID>
<FName>Mary</FName>
<LName>Jacobs</LName>
<DOB>1961-12-01T00:00:00</DOB>
<Sex>70</Sex>
</Employee>
<Employee>
<ID>3</ID>
<FName>Amber</FName>
<LName>Agar</LName>
<DOB>1971-12-05T00:00:00</DOB>
<Sex>77</Sex>
</Employee>
<Employee>
<ID>4</ID>
<FName>Kathy</FName>
<LName>Berry</LName>
<DOB>1976-06-11T00:00:00</DOB>
<Sex>70</Sex>
</Employee>
<Employee>
<ID>5</ID>
<FName>Lena</FName>
<LName>Bilton</LName>
<DOB>1978-11-05T00:00:00</DOB>
<Sex>70</Sex>
</Employee>
</ArrayOfEmployee>
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Rikrop.Core.Serialization.Xml
{
public static class XmlSerializers
{
private static readonly ConcurrentDictionary<Type, XmlSerializer> serializers = new ConcurrentDictionary<Type, XmlSerializer>();
private static readonly XmlSerializerNamespaces xns = new XmlSerializerNamespaces();
private static readonly UTF8Encoding defaultEncoding = new UTF8Encoding(false);
static XmlSerializers()
{
xns.Add("", "");
}
private static XmlSerializer GetSerializer(Type type, XmlRootAttribute xmlRoot = null)
{
return serializers.GetOrAdd(type, t => new XmlSerializer(t, xmlRoot));
}
public static byte[] SerializeToBytes<T>(T obj, bool omitXmlDeclaration = true, string customRootName = null, bool omitNamespaces = true, Encoding encoding = null)
{
if (ReferenceEquals(null, obj))
return null;
using (var ms = new MemoryStream())
{
var xmlSettings = new XmlWriterSettings
{
OmitXmlDeclaration = omitXmlDeclaration,
NewLineHandling = NewLineHandling.Entitize,
Indent = true,
Encoding = encoding ?? defaultEncoding
};
using (var xmlWriter = XmlWriter.Create(ms, xmlSettings))
{
var xmlRootNameAttribute = string.IsNullOrEmpty(customRootName) ? null : new XmlRootAttribute(customRootName);
GetSerializer(typeof(T), xmlRootNameAttribute).Serialize(xmlWriter, obj, omitNamespaces ? xns : null);
return ms.ToArray();
}
}
}
public static string Serialize<T>(T obj, bool omitNamespaces = true, Encoding encoding = null, bool omitXmlDeclaration = true, string customRootName = null)
{
var bytes = SerializeToBytes(obj, omitXmlDeclaration, customRootName, omitNamespaces, encoding);
return (encoding ?? defaultEncoding).GetString(bytes);
}
public static string SafeSerialize<T>(T obj, bool omitNamespaces = true, Encoding encoding = null, bool omitXmlDeclaration = true, string customRootName = null)
{
try
{
return Serialize(obj, omitNamespaces, encoding, omitXmlDeclaration, customRootName);
}
catch (Exception e)
{
// log error here
}
return null;
}
public static T SafeDeserialize<T>(byte[] serializedData, Encoding encoding = null, bool silentMode = false)
where T : class
{
try
{
return DeserializeFromBytes<T>(serializedData, encoding);
}
catch (Exception e)
{
if (!silentMode)
{
// log error here
}
}
return null;
}
public static T SafeDeserialize<T>(string serializedData, Encoding encoding = null, bool silentMode = false)
where T : class
{
try
{
return Deserialize<T>(serializedData, encoding);
}
catch (Exception e)
{
if (!silentMode)
{
// log error here
}
}
return null;
}
public static T DeserializeFromBytes<T>(byte[] serializedData, Encoding encoding = null) where T : class
{
using (var sr = new StreamReader(new MemoryStream(serializedData), encoding ?? defaultEncoding))
using (var xmlReader = XmlReader.Create(sr))
return (T) GetSerializer(typeof(T)).Deserialize(xmlReader);
}
public static T Deserialize<T>(string stringData, Encoding encoding = null) where T : class
{
var bytes = (encoding ?? defaultEncoding).GetBytes(stringData);
return DeserializeFromBytes<T>(bytes, encoding);
}
}
}
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Rikrop.Core.Serialization.Xml
{
public static class XmlSerializers
{
private static readonly ConcurrentDictionary<Type, XmlSerializer> serializers = new ConcurrentDictionary<Type, XmlSerializer>();
private static readonly XmlSerializerNamespaces xnameSpace = new XmlSerializerNamespaces();
private static readonly UTF8Encoding defaultEncoding = new UTF8Encoding(false);
static XmlSerializers()
{
xnameSpace.Add("", "");
}
private static XmlSerializer GetSerializer(Type type)
{
return serializers.GetOrAdd(type, t => new XmlSerializer(t));
}
public static byte[] Serialize(object obj, bool omitNamespaces = false, Encoding encoding = null)
{
if (ReferenceEquals(null, obj))
return null;
using (var stream = new MemoryStream())
{
using (var xmlWriter = XmlWriter.Create(stream, new XmlWriterSettings { OmitXmlDeclaration = false, Encoding = encoding ?? defaultEncoding, Indent = true}))
{
GetSerializer(obj.GetType()).Serialize(xmlWriter, obj, omitNamespaces ? xnameSpace : null);
return stream.ToArray();
}
}
}
public static string SerializeToString(object obj, bool omitNamespaces = false, Encoding encoding = null)
{
var bytes = Serialize(obj, omitNamespaces, encoding);
return (encoding ?? defaultEncoding).GetString(bytes);
}
public static TData Deserialize<TData>(byte[] serializedData, Encoding encoding = null) where TData : class
{
using (var sr = new StreamReader(new MemoryStream(serializedData), encoding ?? defaultEncoding))
using (var xmlReader = XmlReader.Create(sr))
return (TData)GetSerializer(typeof(TData)).Deserialize(xmlReader);
}
public static TData DeserializeFromString<TData>(string stringData, Encoding encoding = null) where TData : class
{
var bytes = (encoding ?? defaultEncoding).GetBytes(stringData);
return Deserialize<TData>(bytes);
}
}
}