I am struggling to work with XDocument to parse some data and change some values for docx file. I am able to download the file, I am able to parse the file, then I can replace those nodes in question but then when it comes to saving the file it always corrupts it. When I compare docText in the code below to the parsed values if I did .ToString() and compare what parse does, it adds some additional tags (xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main") which i am wondering if parse cannot be reused to go backwards back to the docx file. My code is as follows:
using (var memoryStream = await oneDrive.DriveItemDownloadAsync(SharedDriveID, filePathSourceMemo, "path"))
{
var DraftDocumentMemoryStream = new MemoryStream();
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memoryStream, true))
{
docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
try
{
var xDoc = XDocument.Parse(docText);
xDoc.Save(DraftDocumentMemoryStream);
DraftDocumentMemoryStream.Position = 0;
}
catch (Exception ex)
{
}
}
var UploadResponse = await oneDrive.UploadFileStreamAsync(SharedDriveID, DraftDocumentMemoryStream, filePathDestinationMemo, "replace");
}
I know my download and upload functions for MS Graph API work as I have saved streams from WordProcessingDocument directly and it always is good. Its this xml parser that seems to break things when i got to save as a stream. I also am not able to reopen those xdocument streams in WordProcessingDocument because it will then say file is corrupt.