Changing Word Document XML

nah0nah

New Member
What I am doing is trying to change the value of a Microsoft Office Word documents XML and save it as a new file. I know that there are SDK's that I could use to make this easier but the project I am tasked with maintaining is doing things this way and I was told I had to as well. I have a basic test document with two placeholders mapped to the following XML: \[code\]<root> <element> Fubar </element> <second> This is the second placeholder </second></root>\[/code\]In my test project I have the following:\[code\]string strRelRoot = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";//the word templatebyte[] buffer = File.ReadAllBytes("dev.docx");MemoryStream stream = new MemoryStream(buffer, true);Package package = Package.Open(stream, FileMode.Open, FileAccess.ReadWrite);//get the document relationshipPackageRelationshipCollection pkgrcOfficeDocument = package.GetRelationshipsByType(strRelRoot);//iterate through relationshipforeach (PackageRelationship pkgr in pkgrcOfficeDocument){ if (pkgr.SourceUri.OriginalString == "/") { //uri for the custom xml Uri uriData = http://stackoverflow.com/questions/11432388/new Uri("/customXML/item1.xml", UriKind.Relative); //delete the existing xml if it exists if (package.PartExists(uriData)) { // Delete template "/customXML/item1.xml" part package.DeletePart(uriData); } PackagePart pkgprtData = http://stackoverflow.com/questions/11432388/package.CreatePart(uriData,"application/xml"); //hard coded test data string xml = @"<root> <element> Changed </element> <second> The second placeholder changed </second> </root>"; Stream fromStream = pkgprtData.GetStream(); //write the string fromStream.Write(Encoding.UTF8.GetBytes(xml),0,xml.Length); //destination file Stream dest = File.Create("test.docx"); //write to the destination file for (int a = fromStream.ReadByte(); a != -1; a = fromStream.ReadByte()) { dest.WriteByte((byte)a); } }}\[/code\]What is happening right now is the file test.docx is being created but it is a blank document. I'm not sure why this is happening. Any suggestions anyone could offer on this approach and/or what I am doing incorrectly would be very much appreciated. Thanks much!
 
Back
Top