方法一:指定对象
private string ToGatheringEMXML(GatheringEMEntity entity)
{
string retSerialXml = "";
System.IO.MemoryStream StreamRequest = new System.IO.MemoryStream();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(GatheringEMEntity));
System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(StreamRequest, entity, ns);
retSerialXml = System.Text.Encoding.UTF8.GetString(StreamRequest.GetBuffer());
return retSerialXml;
}
方法二:不指定对象,通用方法
#region [ SerilaizeToString ]
public override string SerializeToString(object obj, System.Type[] extraTypes, Encoding encoding)
{
string serializedString = string.Empty;
if (obj != null)
{
XmlSerializer serializer = s_XmlSerializerCache.GetSerializer(obj.GetType(), extraTypes);
serializedString = SerializeToString(serializer, obj, encoding);
}
return serializedString;
}
#endregion
public XmlSerializer GetSerializer(Type type, Type[] knownTypes)
{
XmlSerializer serializer = null;
XmlSerializerCacheKey key = new XmlSerializerCacheKey(type,
knownTypes);
if (!_serializers.ContainsKey(key))
{
lock (_syncRoot)
{
if (!_serializers.ContainsKey(key))
{
serializer = knownTypes == null ? new
XmlSerializer(type) : new XmlSerializer(type, knownTypes);
_serializers.Add(key, serializer);
return serializer;
}
}
}
serializer = this._serializers[key];
return serializer;
}
protected string SerializeToString(XmlSerializer serializer, object obj, Encoding encoding)
{
StringBuilder sb = new StringBuilder();
using (TextWriter writer = new EncodedStringWriter(sb, encoding))
{
XmlTextWriter xtw = new XmlTextWriter(writer);
if (SerializationSettings.Current.Indent)
{
xtw.Formatting = Formatting.Indented;
xtw.Indentation = 2;
}
XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
xmlns.Add(string.Empty, string.Empty);
serializer.Serialize(xtw, obj, xmlns);
}
return sb.ToString();
}