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)
        // 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;
            // Find the custom xml namespace
            customXmlNamespace = document.Application.XMLNamespaces.get_Item(ref 
        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", 
        throw new ApplicationException(attachFailed);


Share This Post it!

digg it!





Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s