I'm using XML to store data and I need to store a string array in it. The best way (that I can think of) to store a string array is by converting it to a single string. In order to do that, I'm using string.Join
to join the strings with \0
and then use Base64 so that the \0
(and any other special character) can be retrieved easier. Because it's possible that a string in a array already has \0
in it (causing another string to be the array when they're converted back to an array), I'm escaping the existing \0
by first adding another backslash to existing backslashes and changing \0
to \\0
. Is there any better way to do this? Should I be using \r\n
instead (but wouldn't that also be the same as using \0
)? I should also note that its so I can use IXmlSerializable and it is also storing byte[]
, uint
, ulong
and string
in the XML as well.
Retrieving String Array (Via XML)
this.Name = reader.GetAttribute("Name");
string strType = reader.GetAttribute("Type");
byte[] buffer = new byte[1000];
int readBytes = 0;
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
while ((readBytes = reader.ReadElementContentAsBase64(buffer, 0, 50)) > 0)
{
bw.Write(buffer, 0, readBytes);
}
bw.Close();
List<string> unescapedStrs = new List<string>();
string[] val = strValue.Split('\0');
string newStr;
foreach (string s in val)
{
newStr = Regex.Replace(s, @"([^\\])(\\0)", "$1\0").Replace("\\\\", "\\");
unescapedStrs.Add(newStr);
}
if (val.Length > 0)
this.Value = unescapedStrs.ToArray();
Storing String Array (Via XML)
writer.WriteAttributeString("Name", this.Name);
writer.WriteAttributeString("Type", this.Type);
string strValue = string.Empty;
string[] val = (string[])this.Value;
List<string> escapedStrs = new List<string>();
foreach (string s in val)
{
string newStr = s;
// Escape backslashes so existing \\0 don't get mixed up
if (newStr.IndexOf('\\') > 0)
newStr = newStr.Replace("\\", "\\\\");
// If theres NULL chars in strings already, escape them
if (newStr.IndexOf('\0') > 0)
newStr = newStr.Replace("\0", "\\0");
escapedStrs.Add(newStr);
}
strValue = string.Join("\0", escapedStrs.ToArray());
int byteLen = Encoding.Unicode.GetByteCount(strValue);
byte[] bytes = Encoding.Unicode.GetBytes(strValue);
writer.WriteBase64(bytes, 0, byteLen);
XMLReader
,XMLWriter
,XMLDocument
\$\endgroup\$