我目前有一个可序列化的对象,我将其作为XML存储在数据库中。这是一个包含一些变量的简单小类。它看起来像这样:
[Serializable]
public class ExampleClassToSerialize
{
public bool ImABool;
public int ImAnInt;
public string ImAString;
}
当我静态指定对象的类型(ExampleClassToSerialize类型)时,它工作正常。但后来我添加了另一个可序列化的类,并希望使该方法更通用...并且用它度过了一段可怕的时光!我尝试传入一个对象并执行“typeof”但是没有用完,所以我尝试将类型作为Type对象传递...也没有去。这就是我到目前为止所做的:
//Returns a generic item from the Table
private bool GetXMLControlTextFromDB(string objectToGet, object objectToFill, Type type)
{
try
{
// Grab object from stored procedure
using (SqlConnection conn = My_Connection)
using (SqlCommand cmd = new SqlCommand("[dbo].[spGetStuffFromTable]", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TehObjectorz", objectToGet));
conn.Open();
string serializedObject = cmd.ExecuteScalar().ToString();
conn.Close();
//Deserialize the object pulled from DB
try
{
if (serializedObject != "")
{
var serializer = new XmlSerializer(type);
using (var reader = new StringReader(serializedObject))
{
objectToFill = Convert.ChangeType(serializer.Deserialize(reader), type);
}
return true;
}
else
return false;
}
catch (Exception ex)
{
//Do Stuff with exception
Return false;
}
}
}
catch (Exception ex)
{
//Do more stuff with exception
Return false;
}
}
当我运行它时,我收到以下错误:
Source: System.Xml
Message: There is an error in XML document (1, 1).
有人能想到更好的方法吗?
谢谢!
更新:
-InnerException
{"Data at the root level is invalid. Line 1, position 1."}
System.Exception {System.Xml.XmlException}
StackTrace "at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)\r\n
at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)\r\n
at Namespace.GetXMLObjectFromDB(String objectToGet, Object objectToFill, Type type) in *stuff*\ProjectFile.cs 2081"
string
注:
问题是我在更改类型之前工作正常。当我做的时候
var serializer = new XmlSerializer(ExampleClassToSerialize.GetType());
和
objectToFill = (ExampleClassToSerialize)serializer.Deserialize(reader);
它工作正常:(只有当我尝试执行此运行时确定转换它开始失败。