Modifying The Contents of CustomXML Part
I've spent much of the day frustrated using System.IO.Packaging to do a simple thing, modify the contents of a customXML part. It seemed like a simple thing to do really but I was misled and under the false assumption that one had to delete the part and recreate the part. For whatever reason, I never figured out, everytime I deleted the customXML part, the relationship went with it and broke my bindings. With confirmation that this shouldn't be happening from “the inside,” I went back to my original code from 6am this morning, simply overwriting the part that already existed. Working with ever changing beta code... always fun:
So here's the code snippet for overwriting a customXML part (note that I based this on the assumption of only one customXML part -- you'd need to check for multiple parts):
string xmlDocRelType = @"http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml";
string officeDocRelType = @“http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument“;
PackagePart xmlPart = null;
PackagePart documentPart = null;
Uri documentUri = null;
Uri xmlUri = null;
//open the package
using (Package officePackage = Package.Open(docPath, FileMode.Open, FileAccess.ReadWrite))
{
//find the document part
foreach (PackageRelationship relationship in officePackage.GetRelationshipsByType(officeDocRelType))
{
//only one document part
documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
documentPart = officePackage.GetPart(documentUri);
break;
}
XmlDocument partDoc;
//find the custom XML Uri
foreach(PackageRelationship relationship in documentPart.GetRelationshipsByType(xmlDocRelType))
{
//TODO: add namespace check as will have more than one
//custom XML in solution
xmlUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
break;
}
//get the customXML part
xmlPart = officePackage.GetPart(xmlUri);
//modify the contents of the part
Stream outputStream = xmlPart.GetStream(FileMode.Create, FileAccess.ReadWrite);
StreamWriter ts = new StreamWriter(outputStream);
ts.Write(xmlDoc);
ts.Flush();
ts.Close();
//close our package up
officePackage.Close();
}