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 OpenXmlDeveloper.org), 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:customXMLPart.Load("MyCustomXML.xml");
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.
I am trying the following:
- add a new CustomXmlPart
- add a schema to this part's SchemaCollection
part = Globals.ThisAddIn.Application.ActiveDocument.CustomXMLParts.Add ("(some xml goes here)", System.Reflection.Missing.Value);
part.SchemaCollection.Add (NameSpaceUri, "SchemaAlias", "(path to xsd file)", false);
When doing the SchemaCollection.Ad, I get the following exception:
"System.Runtime.InteropServices.COMException (0xE0041802): This schema cannot be reloaded, as the schema collection is currently in use."
The SchemaCollection of the newly created CustomXmlPart is empty.
What is going wrong here?