我重新使用了一些旧的代码(我认为是较旧的.net版本),用于从xml反序列化一个对象(最后我将粘贴用于序列化对象的代码)
这是代码:
/// <summary>
/// Reconstruct an object from an XML string
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static T DeserializeObject<T>(string xml)
{
using (MemoryStream stream = new MemoryStream(StringToUTF8ByteArray(xml)))
using (new XmlTextWriter(stream, Encoding.UTF8))
{
return (T)new XmlSerializer(typeof(T)).Deserialize(stream);
}
}
它给了我这个错误:'Memory stream is not expandable
'在返回行。
出了什么问题?
这是序列化代码:
MemoryStream stream = new MemoryStream();
using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.UTF8))
{
XmlSerializer xs = new XmlSerializer(item.GetType());
xs.Serialize(xml, item);
stream = (MemoryStream)xml.BaseStream;
}
return UTF8ByteArrayToString(stream.ToArray());
修改
这是缺失的功能
private static Byte[] StringToUTF8ByteArray(string pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
答案 0 :(得分:6)
首先,您要从XML创建MemoryStream
到读取。然后,您正在为该流创建XmlTextWriter
到写。为什么呢?
我怀疑你可以摆脱第二个使用声明:
using (MemoryStream stream = new MemoryStream(StringToUTF8ByteArray(xml)))
{
return (T)new XmlSerializer(typeof(T)).Deserialize(stream);
}
话虽如此,你的StringToUTF8ByteArray
方法做什么并不清楚 - 它只是:
return Encoding.UTF8.GetBytes(text);
?如果是这样,那可能不是正确的做法 - 如果原始XML是在其他编码中,那么XML声明会说一件事,而流将包含用另一种编码编码的文本。 .. 不好。你可能会更好:
using (TextReader reader = new StringReader(xml))
{
return (T)new XmlSerializer(typeof(T)).Deserialize(XmlReader.Create(reader));
}
答案 1 :(得分:1)
看起来您可能需要XmlTextReader而不是XmlTextWriter?我用它来序列化到一个文件。您可能想要使用类似的东西:
/// <summary>
/// Serialize an object into XML and save to a file
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="filePath"></param>
public static void SerializeToXml<T>(T value, string filePath) where T : class
{
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
x.Serialize(stream, value);
}
}
/// <summary>
/// Deserialize an XML File into an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="filePath"></param>
/// <returns></returns>
public static T DeserializeFromXml<T>(string filePath) where T : class
{
using (StreamReader stream = new StreamReader(filePath))
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
return (T)x.Deserialize(stream);
}
}