C# XML Serialization/DeSerialization [closed]
I'm having a look at XML Serialization and have serialized as such:
public static string Serialize<T>(T data)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
//Overridden to use UTF8 for compatability with Perl XML::DOM
StringWriterUTF8 sw = new StringWriterUTF8();
xmlSerializer.Serialize(sw, data);
return sw.ToString();
}
I use it as such:
string serializedData = Serializer.Serialize<List<InputData>>(rawDataCollection);
Which produces:
<ArrayOfInputData xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InputDat开发者_如何学Goa>
<dose>100mg/kg</dose>
<compound>AZ13279746-001</compound>
</InputData>
</ArrayOfInputData>
For some reason, I can't include the header which was xml version 1.0 encoding UTF8.
Now, when I try to deserialize with
public static object DeSerialize<T>(string data)
{
StringReader rdr = new StringReader(data);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
T i;
i = (T)xmlSerializer.Deserialize(rdr);
return i;
}
I get an error saying invalid xml at 2,2. Any idea what I am doing wrong?
Thanks
Have now fixed it:
public static object DeSerialize<T>(string data)
{
StringReader rdr = new StringReader(data);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
var result = (T)xmlSerializer.Deserialize(rdr);
return result;
}
var fl = (List<InputData>)Serializer.DeSerialize<List<InputData>>(serializedData);
Not sure if it's a typo, or a genuine mistake in the output, but you have an erroneous space in your XML.
< /ArrayOfInputData>
精彩评论