title: Manipulating Word 2007 Document XML in C#
body: <p>I am trying to manipulate the XML of a Word 2007 document in C#. I have managed to find and manipulate the node that I want but now I can't seem to figure out how to save it back. Here is what I am trying:</p>
  
  <pre><code>// Open the document  from memoryStream
  Package pkgFile = Package.Open(memoryStream, FileMode.Open, FileAccess.ReadWrite);
  PackageRelationshipCollection pkgrcOfficeDocument = pkgFile.GetRelationshipsByType(strRelRoot);
  
  foreach (PackageRelationship pkgr in pkgrcOfficeDocument)
  {
      if (pkgr.SourceUri.OriginalString == "/")
      {
          Uri uriData = new Uri("/word/document.xml", UriKind.Relative);
  
          PackagePart pkgprtData = pkgFile.GetPart(uriData);
  
          XmlDocument doc = new XmlDocument();
          doc.Load(pkgprtData.GetStream());
  
          NameTable nt = new NameTable();
          XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
          nsManager.AddNamespace("w", nsUri);
  
          XmlNodeList nodes = doc.SelectNodes("//w:body/w:p/w:r/w:t", nsManager);
  
          foreach (XmlNode node in nodes)
          {
              if (node.InnerText == "{{TextToChange}}")
              {
                  node.InnerText = "success";
              }
          }
  
  
          if (pkgFile.PartExists(uriData))
          {
              // Delete template "/customXML/item1.xml" part
              pkgFile.DeletePart(uriData);
          }
          PackagePart newPkgprtData = pkgFile.CreatePart(uriData, "application/xml");
          StreamWriter partWrtr = new StreamWriter(newPkgprtData.GetStream(FileMode.Create, FileAccess.Write));
  
          doc.Save(partWrtr);
          partWrtr.Close();
      }
  }   
  
  pkgFile.Close();
  </code></pre>
  
  <p>I get the error 'Memory stream is not expandable'.  Any ideas?</p>