XML 文件仅包含名为 ObjectProxy - C# XML 序列化的空白元素



我已经将XML序列化添加到我的项目中,以便将我的对象数据存储在XML文件中。

我使用以下帮助程序类来实现此目的:

public static class SerializerHelper
{
/// <summary>
/// Serializes an object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializableObject"></param>
/// <param name="fileName"></param>
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(
"SerializerHelper.cs");
public static void SerializeObject<T>(string filepath, T serializableObject)
{
if (serializableObject == null) { return; }
try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(filepath);
stream.Close();
}
}
catch (Exception ex)
{
//Log exception here
logger.Error("Error Serializing: " + ex.Message);
}
}

/// <summary>
/// Deserializes an xml file into an object list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public static T DeSerializeObject<T>(string filepath)
{
T objectOut = default(T);
if (!System.IO.File.Exists(filepath)) return objectOut;
try
{
string attributeXml = string.Empty;
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(filepath);
string xmlString = xmlDocument.OuterXml;
using (StringReader read = new StringReader(xmlString))
{
Type outType = typeof(T);
XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (T)serializer.Deserialize(reader);
reader.Close();
}
read.Close();
}
}
catch (Exception ex)
{
//Log exception here
logger.Error("Error Deserializing: " + ex.Message);
}
return objectOut;
}
}

在我的方法中,在我创建/删除/更改对象的任何地方,我都使用如下代码来序列化对象数据:

//Increments the failed logon attempts counter
public void incrementFailedLogonAttempts()
{
logonAttemptCounter.incrementFailedLogons();
//Update the failed logon attempt counter in the XML Data Store
SerializerHelper.SerializeObject(@"C:UsersMichael"
+ @"Google DriveFDM Dev Course ContentWorkspaceSystemAdminSystemAdmin"
+ @"XML Data StoreLogonAttemptCounter.xml", logonAttemptCounter);
}

但是,在运行所有单元测试之后,我的一些 XML 文件(在运行所有测试之前已很好地序列化)现在如下所示:

<?xml version="1.0"?>
<ObjectProxy_4 xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>

有谁知道这里可能出了什么问题?或者为什么会出错?

任何帮助将不胜感激!

我想我实际上知道。我的测试使用模拟对象来模拟依赖项。在我的许多测试中,我创建了要测试其方法的对象,在构造函数中注入了模拟对象。这是导致问题的原因吗?我正在序列化模拟对象,根据定义,这些对象是空的?

最新更新