title: How to stream (load) an XML file, modify XML Element data, and write to MemoryStream
body: <p>I have requirements to load large XML files (between 0.5MB - 600MB), decrypt data that is within the XML file, and write that to a MemoryStream.</p>
  
  <p>It's important that the decrypted data doesn't rest on disk.</p>
  
  <p>Below is my current implementation which loads the entire XML document into memory, decrypts the card number and sets the value, and then copies the modified XML document to a <code>MemoryStream</code>. However, this implementation isn't feasible as it loads the entire XML document into RAM.</p>
  
  <pre><code>public MemoryStream DecryptFile(string xmlFullPath, DateTime encryptionKey)
  {
      XNamespace xmlNameSpace = "http://www.xml.com/schema";
  
      XDocument fileXDocument = XDocument.Load(xmlFullPath);
  
      IEnumerable&lt;XElement&gt; cardElements =
          fileXDocument
          .Descendants(xmlNameSpace + "card");
  
      // Iterate over each &lt;card&gt; element within the &lt;batchRequest&gt;.
      foreach (XElement cardElement in cardElements)
      {
          XElement cardNumberElement = cardElement.Element(xmlNameSpace + "number");
  
          // Read encrypted value
          // Decrypt value
  
          cardNumberElement.SetValue(decryptedCreditCard);
      }
  
      // Save the XML document, with the decrypted cards, to a memory stream.
      var memoryStream = new MemoryStream();
  
      fileXDocument.Save(memoryStream, SaveOptions.DisableFormatting);
  
      // Rewind the stream, so that it's ready to be read from it elsewhere.
      memoryStream.Position = 0;
  
      return memoryStream;
  }
  </code></pre>
  
  <p>I'm pretty familiar with the <a href="https://msdn.microsoft.com/en-us/library/system.xml.xmlreader.read(v=vs.110).aspx" rel="nofollow noreferrer"><code>XmlReader</code></a>, and I'm using it for other operations.</p>
  
  <p>I've thought about being able to run through the XML document, and simply write out element-by-element to a corresponding MemoryStream, and eventually decrypt the data and write that to the memory stream as the card numbers appear.</p>
  
  <p>However, I am unable to get the raw XML of the start/end element that I'm iterating on. At least, without parsing/loading the entire element, which an operation like ReadOuterXml allows. But I don't want to read the entire element. I simply want to write the raw element-by-element to the MemoryStream, and only handle decrypting the card number's as I come across them.</p>
  
  <p>Note that the card number's are within a serialized object "transaction". i.e. <code>&lt;transaction&gt;...&lt;number&gt;asdfa3423jasfa&lt;/number&gt;&lt;/transaction&gt;</code></p>
  
  <p>So, how can I load (stream) an XML file, modify bits of data in it, and progressively write the content to a MemoryStream?</p>