August 24, 2005

Reading BinHex encoded data out of XmlDocument

It's surprisingly tricky to get BinHex encoded data out of XmlDocument tree in .NET 1.X. XmlConvert class, which apparently has to support such conversions has a method FromBinHexString(), but weird - it only public for .NET Compact Framework. It's internal for regular .NET Framework. It's obvious that lots of .NET ...

XmlTextReader can handle BinHex data just fine. So all you need is to get BinHex data out of XmlDocument along with containing element as string and read it with XmlTextReader:

XmlDocument doc = new XmlDocument();
doc.Load("foo.xml");
XmlNode dataNode = doc.SelectSingleNode("/data");
XmlTextReader r = new XmlTextReader(new StringReader(dataNode.OuterXml));
r.MoveToContent();
do 
{
  byte[] buf  = new byte[1024];
  int bytesRead = r.ReadBinHex(buf, 0, buf.Length);
  string data = new string(Encoding.UTF8.GetChars(buf, 0, bytesRead));
  Console.WriteLine(data);
} while (r.Name == "data");