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();
XmlNode dataNode = doc.SelectSingleNode("/data");
XmlTextReader r = new XmlTextReader(new StringReader(dataNode.OuterXml));
  byte[] buf  = new byte[1024];
  int bytesRead = r.ReadBinHex(buf, 0, buf.Length);
  string data = new string(Encoding.UTF8.GetChars(buf, 0, bytesRead));
} while (r.Name == "data");