Compact Binary encoding of XML Infoset using MC-NBFX?

596 views Asked by At

Microsoft implemented their own compact binary XML encoding (MC-NBFX) which is an option within WCF for conveying XML Infosets (e.g. SOAP requests and responses) more efficiently than the standard XML text encoding(s).

I would like to use the same encoding for use generally, e.g. to save a large XML file to disk in a compact binary form.

I started out with:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(@"<Foo><Bar>abc</Bar></Foo>");

using(FileStream fs = new FileStream("c:/tmp/foo.bin", FileMode.Create))
{
    using(XmlDictionaryWriter xbw = XmlDictionaryWriter.CreateBinaryWriter(fs))
    {
        xmlDoc.WriteTo(xbw);
    }
}

This does indeed output an MC-NBFX format file, but if I encode an XML document with repeating strings (e.g. element names), those names appear multiple times in the binary file.

The point of XmlDictionaryWriter is that it allows a dictionary of strings to be defined and to replace strings in the stream with a string ID. There are actually two dictionaries, one can be passed to CreateBinaryWriter() and is intended to be a predetermined/static dictionary. I tried plugging in such a static dictionary, but the encoder is ignoring it:

XmlDictionary xmlDictionary = new XmlDictionary();
xmlDictionary.Add("Foo");
xmlDictionary.Add("Bar");

using(XmlDictionaryWriter xbw = XmlDictionaryWriter.CreateBinaryWriter(fs, xmlDictionary))
{
    xmlDoc.WriteTo(xbw);
}

The second type of dictionary is dynamic, and supposedly has strings added to it during the writing process. To use this mechanism requires use of (and perhaps overriding of) XmlBinaryWriterSession. E.g.:

XmlBinaryWriterSession writerSession = new XmlBinaryWriterSession();
using(XmlDictionaryWriter xbw = XmlDictionaryWriter.CreateBinaryWriter(fs, null, writerSession))
{
    xmlDoc.WriteTo(xbw);
}

Again, this has no effect on the output, repeating strings still occur and the dictionary within XmlBinaryWriterSession is seen to be empty after the writing has completed. I was expecting to have to override XmlBinaryWriterSession in order to extract the contents of the dynamic dictionary, so that I can then convey those with the encoded XML (MC-NBFX doesn't cover this, by I am happy to encode the dictionary myself if necessary).

The documentation for these classes is minimal. Are they intended to be used this way, if so where am I going wrong?

Thanks.

0

There are 0 answers