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?.
1 Answer
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?
1 Comment
AravindK
thank you. But we need to expose some of the data to user and it should be in neat and structured way because of that we chosen to implement XML in our project..