Attach a Custom XML Schema to a Word Document Programmatically

If you find the need to add a custom XML schema to a Word document or other Office document programmatically, this function might come in handy.  This function uses the Word InterOp assemblies to attach a schema to a document.

using System;
using System.Xml;
using System.Xml.Schema;

using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
...

/// <summary>
/// Attaches a custom xml schema to a document
/// </summary>
/// <param name="document">The Word document to modify</param>
/// <param name="schemaUrl">The url to the schema</param>
/// <param name="schemaNamespaceUri">The schema namespace defined in the schema</param>
/// <param name="schemaAlias">The alias used for the schema</param>
public static void AttachCustomXmlSchema(Word.Document document, string schemaUrl, 
            string schemaNamespaceUri, string schemaAlias)
{
    try
    {
        // Objects to use when passing strings as ref to word
        object schemaNamespaceUriObj = schemaNamespaceUri;
        object schemaAliasObj = schemaAlias;

        // Find the custom xml namespace (if we have one declared)
        Word.XMLNamespace customXmlNamespace = null;
        try
        {
            // Find the custom xml namespace
            customXmlNamespace = document.Application.XMLNamespaces.get_Item(ref 
                        schemaNamespaceUriObj);
        }
        catch { };

        // Did we find it the namespace?
        if (customXmlNamespace == null)
        {
            // We didn't find it
            // Add the custom xml schema to the available namespaces
            customXmlNamespace = document.Application.XMLNamespaces.Add(schemaUrl, 
                        ref schemaNamespaceUriObj, ref schemaAliasObj, true);
        }

        // Attach the custom xml schema to the document
        object documentObj = document;
        customXmlNamespace.AttachToDocument(ref documentObj);
    }
    catch (Exception ex)
    {
        string attachFailed = string.Format("Unable to attach the {0} xml schema", 
                schemaAlias);
        throw new ApplicationException(attachFailed);
    }
}

 

Share This Post

del.icio.us it!

digg it!

reddit!

technorati!

yahoo!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s