要重写一下WriteEndElement方法:
public class XmlTextWriterEE : XmlTextWriter
{
public XmlTextWriterEE(TextWriter sink)
: base(sink)
{
}
public override void WriteEndElement()
{
base.WriteFullEndElement();
}
}
序列化时,如下使用:
public static string SerializeXML<T>(string xmlFileFullPath, T entity)
{
string errorMsg = string.Empty;
if (string.IsNullOrEmpty(xmlFileFullPath))
{
return "xmlFileFullPath 参数不能为空";
}
try
{
XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
xsn.Add(String.Empty, String.Empty);
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StreamWriter(xmlFileFullPath, false, Encoding.UTF8))
{
var xmlTextWrite = new XmlTextWriterEE(writer);
xmlTextWrite.Formatting = Formatting.Indented;
serializer.Serialize(xmlTextWrite, entity, xsn);
writer.Close();
}
//using (FileStream fs = new FileStream(xmlFileFullPath, FileMode.Create))
//{
// XmlSerializer formatter = new XmlSerializer(typeof(T));
// formatter.Serialize(fs, entity);
//}
return "";
}
catch (Exception ex)
{
errorMsg = ex.Message;
}
return errorMsg;
}
顺带把发序列化也给写上:
public static T DeserializeXML<T>(string xmlFileContent) where T : class
{
if (string.IsNullOrEmpty(xmlFileContent))
{
return default(T);
}
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(EscapeXmlText(ref xmlFileContent)) as T;
}
catch
{
}
return default(T);
}