Reputation: 151
In XML how to store the binary data into the file. and same-way i need to fetch the data. I have tried with some other example codes but i'm not able to store the data. i need more information on XML file and sample code for read and write code for XML. is that best way to store large binary data into the XML file?.
Upvotes: 0
Views: 1298
Reputation: 92
Base64 is a good way of doing that. It's a way of making binary data into text that you can save.
Write:
public void WriteBinaryToXElement( XElement element, byte[] data )
=> element.Value = Convert.ToBase64String( data, 0, data.length );
Read:
public byte[] ReadBinaryFromXElement( XElement element )
=> Convert.FromBase64String( element.Value );
How to use:
// load XML
XElement rootNode = XElement.Load( @"Path\to\XML" );
// find nodes
foreach ( var binaryNode in XElement.Element( "DataNodes" ).Elements() )
{
// read data
byte[] data = ReadBinaryFromXElement( binaryNode );
// do stuff with data
// save back to XML
WriteBinaryToXElement( binaryNode, data );
}
I'm not quite sure if it's a very good idea to do this though. why not just save the binary data in binary files?
Upvotes: 3