我有一个序列化的某种类型的数组。有没有一种方法可以将新对象附加到这个序列化的数组中(以序列化的形式),而不需要将已经保存的集合读取到内存中?
示例:
我有一个包含10^12个元素的file.xml序列化实体数组。我需要向序列化文件中添加另外10^5个元素,但我不想读取所有以前的元素,将新元素附加到流中,并将新数组写入流,因为这将非常耗费资源(特别是内存)。
如果它需要一个二进制序列化程序,我不会有任何问题。
发布于 2009-11-07 02:18:29
通常,解决方案是更改XML字节,这样您就不必像反序列化那样读取所有字节。
通常的步骤是:
例如,将整数添加到序列化数组的代码:
// Serialize array - in you case it the stream you read from file.xml
var ints = new[] { 1, 2, 3 };
var arraySerializer = new XmlSerializer(typeof(int[]));
var memoryStream = new MemoryStream(); // File.OpenWrite("file.xml")
arraySerializer.Serialize(new StreamWriter(memoryStream), ints);
// Save the closing node
int sizeOfClosingNode = 13; // In this case: "</ArrayOfInt>".Length
// Change the size to fit your array
// e.g. ("</ArrayOfOtherType>".Length)
// Set the location just before the closing tag
memoryStream.Position = memoryStream.Length - sizeOfClosingNode;
// Store the closing tag bytes
var buffer = new byte[sizeOfClosingNode];
memoryStream.Read(buffer, 0, sizeOfClosingNode);
// Set back to location just before the closing tag.
// In this location the new item will be written.
memoryStream.Position = memoryStream.Length - sizeOfClosingNode;
// Add to serialized array an item
var itemBuilder = new StringBuilder();
// Write the serialized item as string to itemBuilder
new XmlSerializer(typeof(int)).Serialize(new StringWriter(itemBuilder), 4);
// Get the serialized item XML element (strip the XML document declaration)
XElement newXmlItem = XElement.Parse(itemBuilder.ToString());
// Convert the XML to bytes can be written to the file
byte[] bytes = Encoding.Default.GetBytes(newXmlItem.ToString());
// Write new item to file.
memoryStream.Write(bytes, 0, bytes.Length);
// Write the closing tag.
memoryStream.Write(buffer, 0, sizeOfClosingNode);
// Example that it works
memoryStream.Position = 0;
var modifiedArray = (int[]) arraySerializer.Deserialize(memoryStream);
CollectionAssert.AreEqual(new[] { 1, 2, 3, 4 }, modifiedArray);
https://stackoverflow.com/questions/1691386
复制相似问题