title: Serialize object to XmlDocument
body: <p>In order to return useful information in <code>SoapException.Detail</code> for an asmx web service, I took an idea from WCF and created a fault class to contain said useful information.  That fault object is then serialised to the required <code>XmlNode</code> of a thrown <code>SoapException</code>.</p>
  
  <p>I'm wondering whether I have the best code to create the <code>XmlDocument</code> - here is my take on it:</p>
  
  <pre><code>var xmlDocument = new XmlDocument();
  var serializer = new XmlSerializer(typeof(T));
  using (var stream = new MemoryStream())
  {
      serializer.Serialize(stream, theObjectContainingUsefulInformation);
      stream.Flush();
      stream.Seek(0, SeekOrigin.Begin);
  
      xmlDocument.Load(stream);
  }
  </code></pre>
  
  <p>Is there a better way of doing this?</p>
  
  <p><strong>UPDATE:</strong> I actually ended up doing the following, because unless you wrap the XML in a <code>&lt;detail&gt;</code> xml element, you get a <code>SoapHeaderException</code> at the client end:</p>
  
  <pre><code>var serialiseToDocument = new XmlDocument();
  var serializer = new XmlSerializer(typeof(T));
  using (var stream = new MemoryStream())
  {
      serializer.Serialize(stream, e.ExceptionContext);
      stream.Flush();
      stream.Seek(0, SeekOrigin.Begin);
  
      serialiseToDocument.Load(stream);
  }
  
  // Remove the xml declaration
  serialiseToDocument.RemoveChild(serialiseToDocument.FirstChild);
  
  // Memorise the node we want
  var serialisedNode = serialiseToDocument.FirstChild;
  
  // and wrap it in a &lt;detail&gt; element
  var rootNode = serialiseToDocument.CreateNode(XmlNodeType.Element, "detail", "");
  rootNode.AppendChild(serialisedNode);
  </code></pre>
  
  <p><strong>UPDATE 2:</strong> Given John Saunders excellent answer, I've now started using the following:</p>
  
  <pre><code>private static void SerialiseFaultDetail()
  {
      var fault = new ServiceFault
                      {
                          Message = "Exception occurred",
                          ErrorCode = 1010
                      };
  
      // Serialise to the XML document
      var detailDocument = new XmlDocument();
      var nav = detailDocument.CreateNavigator();
  
      if (nav != null)
      {
          using (XmlWriter writer = nav.AppendChild())
          {
              var ser = new XmlSerializer(fault.GetType());
              ser.Serialize(writer, fault);
          }
      }
  
      // Memorise and remove the element we want
      XmlNode infoNode = detailDocument.FirstChild;
      detailDocument.RemoveChild(infoNode);
  
      // Move into a root &lt;detail&gt; element
      var rootNode = detailDocument.AppendChild(detailDocument.CreateNode(XmlNodeType.Element, "detail", ""));
      rootNode.AppendChild(infoNode);
  
      Console.WriteLine(detailDocument.OuterXml);
      Console.ReadKey();
  }
  </code></pre>