Yes, you can. But as the XML file is a text file, any binary data has to be base64-encoded first. Recall that the encoded version will be approximately 1.5 times bigger than the raw binary data. One way to do this is as follows:
Suppose you have the following XML document:
XmlDocument doc = new XmlDocument();
//Create the document structure
XmlNode pics = doc.CreateElement("pictures");
XmlNode pic = doc.CreateElement("picture");
pics.AppendChild(pic);
doc.AppendChild(pics);
Next you read the binary file (in this case an image) and assign it to the XmlElement inner text:
//Read the bitmap.
string data = null;
Bitmap bmp = new Bitmap(@"e:Image.bmp");
using (MemoryStream mem = new MemoryStream())
{
bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp);
//Convert the bytes to a string.
data = Convert.ToBase64String(mem.ToArray());
}
//Save the data and the document.
pic.InnerText = data;
doc.Save(@"e:Image.xml");
To display the image in a PictureBox, you load the document, get the node text and perform the inverse procedure:
//Reload the document and display the image.
doc = new XmlDocument();
doc.Load(@"e:Image.xml");
data = doc.SelectSingleNode("/pictures/picture").InnerText;
using (MemoryStream mem = new MemoryStream(Convert.FromBase64String(data)))
{
//Load the image from the stream.
bmp = Bitmap.FromStream(mem) as Bitmap;
}
//Asign it to a PictureBox
pcImage.Image = bmp;
This was first published in May 2003