1

I'm writing a custom .NET serializer in C# and want to read and write Array objects to XML using XmlReader and XmlWriter. I would like to base64-encode the Array. The arrays may be 1-, 2- or 3-dimensional and the elements are bool or numeric types.

I'm completely stumped. XmlReader and XmlWriter have methods for reading/writing Byte[] arrays as base64 but I can't figure out how to get from an Array to a Byte[] and back.

The arrays could be large so I would prefer a solution that does not involve copying the array or processing one element at a time. Unsafe code and managed or native C++ are fine. I could use something other than base64 if it is safe for XML.

Thanks for any help or hints.

4

4 回答 4

1

You will have different options, depending on what kind of 'Array' you are using. Is it an Array, List<>, or ArrayList?

For List<>, you can use CopyTo() to grab parts of your List and put them into a binary array, which you could then write using XmlWriter. To read them back from the XmlReader, you can then simply use InsertRange to de-serialize the data.

A Reading Example:

// elsewhere
List<byte> bytes;

// in the deserialization
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize]; 
int index = 0;
int numRead = -1;

while (numRead != 0) // actually read stuff
{
    numRead = reader.ReadContentAsBase64(buffer,  bufferSize);
    if (numRead > 0)
    {
        bytes.CopyTo(buffer, index, numRead);
        index += numRead;
    }
}

Note: code above is not tested, but is probably close. You can do something similar, but in reverse, for encoding and writing the data to base64. For other types, you simply need to convert your array into a list of bytes.

To get other types than bytes into a byte array, you'll need to use System.BitConverter. This has two methods that will make you very happy: GetBytes which converts any basic data type into a byte array, and ToXxx, which includes ToInt32 and ToBoolean. You'll be responsible for doing that conversion yourself after you've read in the base64 information or before you write it out.

You can use BitConverter to do the per-bit conversion to a set of bytes, but it's up to you to design an algorithm for converting your arrays to a single byte array and back.

于 2009-03-20T18:50:20.433 回答
0

如果使用 XmlSerializer,则可以在类型为 byte[] 的属性中指定 XmlElementAttribute,并将 DataType 属性设置为“base64Binary”。见这里

于 2009-06-15T15:09:58.283 回答
0

如果您需要由包含 Base-64 文本的单个 XML 元素表示的单个数组,最简单的方法可能是使用BinaryFormatter将您的数据(任意维数的数组、列表等)转换为字节数组,并且然后只需对它进行 base-64 编码并将其粘贴到您的 XML 文件中。我想不出任何其他将任意数组转换为字节数组的简单方法。

于 2009-03-20T22:38:35.330 回答
0

对我最终所做的事情的快速总结:对于序列化,我使用 BinaryWriter 将单个元素写入包含在 MemoryStream 中的字节数组。我将写入分成小块,因此 MemoryStream 数组保持较小。将块编写为具有 base64 编码文本内容的单个 XML 元素。

反序列化几乎是相反的。base64 块被解码为字节数组;字节数组由内存流包装并由 BinaryReader 读取以将元素推送到结果数组中。

于 2009-03-24T19:56:16.683 回答