title: Serializing an object to XML and appending it to XML file
body: <p>I'm trying to convert a (horse) object into an XmlElement so that I can append it to an XML file. This is what I've tried most recently. </p>
  
  <pre><code>        // create writer and serializer to add horse to xml
          var stringwriter = new StringWriter();
          var serializer = new XmlSerializer(horse.GetType());
  
          // serialize horse object to xml 
          serializer.Serialize(stringwriter, horse);
          var xmlStr = stringwriter.ToString();
  
          // format string to xml 
          var horseXml = new XmlDocument();
          horseXml.LoadXml(xmlStr);
  
          // get horse element from horseXml
          var horseEl = horseXml.ChildNodes[0];
  
          // assign xmldb to xml document
          var xmlDb = new XmlDocument();
          xmlDb.Load(xmlDbFilepath);
          XmlNode root = xmlDb.DocumentElement;
  
         // add horseEl to root of xmlDb
          root.AppendChild(horseEl);
          xmlDb.Save(xmlDbFilepath);
  </code></pre>
  
  <p>Unfortunately, once I get to the line, root.AppendChild(horseEl), this throws the following exception: "An exception of type 'System.ArgumentException' occurred in System.Xml.dll but was not handled in user code Additional information: The node to be inserted is from a different document context." </p>
  
  <p>Any advice would be much appreciated!</p>
  
  <p>EDIT: here's a link showing <a href="https://gist.github.com/jekrch/f4e5e06fcf23d78f12ef" rel="nofollow">my horse class and xmldb</a>.</p>