title: Compact Binary encoding of XML Infoset using MC-NBFX?
body: <p>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).</p>
  
  <p>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.</p>
  
  <p>I started out with:</p>
  
  <pre><code>XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.LoadXml(@"&lt;Foo&gt;&lt;Bar&gt;abc&lt;/Bar&gt;&lt;/Foo&gt;");
  
  using(FileStream fs = new FileStream("c:/tmp/foo.bin", FileMode.Create))
  {
      using(XmlDictionaryWriter xbw = XmlDictionaryWriter.CreateBinaryWriter(fs))
      {
          xmlDoc.WriteTo(xbw);
      }
  }
  </code></pre>
  
  <p>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. </p>
  
  <p>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:</p>
  
  <pre><code>XmlDictionary xmlDictionary = new XmlDictionary();
  xmlDictionary.Add("Foo");
  xmlDictionary.Add("Bar");
  
  using(XmlDictionaryWriter xbw = XmlDictionaryWriter.CreateBinaryWriter(fs, xmlDictionary))
  {
      xmlDoc.WriteTo(xbw);
  }
  </code></pre>
  
  <p>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.:</p>
  
  <pre><code>XmlBinaryWriterSession writerSession = new XmlBinaryWriterSession();
  using(XmlDictionaryWriter xbw = XmlDictionaryWriter.CreateBinaryWriter(fs, null, writerSession))
  {
      xmlDoc.WriteTo(xbw);
  }
  </code></pre>
  
  <p>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).</p>
  
  <p>The documentation for these classes is minimal. Are they intended to be used this way, if so where am I going wrong? </p>
  
  <p>Thanks.</p>