0

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

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.