从xml中反序列化对象给出错误:'内存流不可扩展'
本文关键字:内存 可扩展 错误 xml 反序列化 对象 出错 | 更新日期: 2023-09-27 18:05:51
我重新使用了一些旧代码(我认为是旧的。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;
}
首先创建一个MemoryStream
来从XML读取。然后创建一个XmlTextWriter
来写入到该流。为什么?
我怀疑你可以去掉第二个using语句:
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));
}
看起来您可能需要一个XmlTextReader而不是xmltextwwriter ?我用它来序列化到一个文件。您可能需要使用类似的内容:
/// <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);
}
}