Friday, 22 August 2014

convert binary encoded file to xml c#



I am creating a parser for plist files. There are two types of plist files that i need to parse. The first plist file is a standard xml file which I have working. The second is in binary format and I keep getting an error when trying to convert and load the data to xml. this is the error i am getting..



Exception: Data at the root level is invalid. Line 1, position 1.


Here is my code, I have tried different methods for converting the binary data to xml and I keep getting the same error.


File info..


The plist file that is in binary format UTF8. If i edit in a plist editor i get the correct format. e.g.



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://ift.tt/vvUEPL">



<dict>
<key>BuildMachineOSBuild</key>
<string>13C64</string>
</dict>
</plist>

private static Dictionary<string, string> ReadBinary(Stream stream)
{
byte[] binary = StreamToBinary(stream);
XDocument bDocument = BytesToXml(binary);
List<XElement> elementsFromBinary = XmlToList(bDocument);
return ListToDictionary(elementsFromBinary);
}

private static byte[] StreamToBinary(Stream stream)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}

}

private static XDocument BytesToXml(byte[] bytes)
{
XDocument xmlDoc;
xmlDoc = XDocument.Parse(System.Text.Encoding.UTF8.GetString(bytes)); <-- throws exception
return xmlDoc;

}

No comments:

Post a Comment