Adding Custom XML Parts from the Word Object Model

There are several different ways to insert a custom XML part in an Office Open XML documents: you can manually add the part and set the necessary relationships (here's an example of that on, you can use the .NET 3.0 packaging API, or you can use the Office object models from within your C#, VB, or VBA code.

If you're using that last option, you'll probably want to create an empty custom XML part and then fill it with some content, something like this example in C#:

// add an empty custom XML part:
customXMLPart = myDocument.CustomXMLParts.Add(string.Empty, null);

// Load an XML document into the custom XML part:

The only problem is, that doesn't work: it crashes on the Add() method call. It seems that CustomXMLParts.Add is a bit finicky about that second parameter (the schema), and you can't use null there. Instead, you have to use a new (empty) custom XML schema collection, like this:

customXMLPart = myDocument.CustomXMLParts.Add(string.Empty, new Office.CustomXMLSchemaCollectionClass() );

I'm passing this on because it seems that CustomXMLParts is not yet well-documented, and it took quite a while to find this solution. You can get away with omitting the parameters to CustomXMLParts.Add() from within VBA, but if you're writing C# code then you'll need to use the approach described above.