Adding Custom XML Parts from the Word Object Model

Published 16 June 06 06:49 AM

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.

by dmahugh

Comments

# leprino said on June 29, 2006 8:53 AM:
Hi Doug,
You can use <b>System.Reflection.Missing.Value<b> for the second parameter instead of creating a new, empty collection.
Ciao, Paolo
# Qanuc said on October 11, 2006 11:17 AM:

Hi Doug,

I am trying the following:

- add a new CustomXmlPart

- add a schema to this part's SchemaCollection

as follows:

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?

Thanks

 Michael

# Weddings said on June 6, 2008 9:58 AM:

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

New Comments to this post are disabled

This Blog

Syndication

Page view tracker