WordprocessingML document generator with XML Schema tagging

Word documents can be tagged with elements from XML schema and also programmatically inject value into it. With OpenXML SDK and LINQ to XML, all these are even easier! Below are the steps.

Create a schema in Visual Studio

The follow details must be unique

1. targetNamespace

2. xmlns

3. xmlns:mstns

4. name of element and complexType

clip_image002

Open up Word 2007, click on Schema

clip_image004

Click on Add Schema

clip_image006

Select the schema you created just now in file dialog

clip_image008

Enter an alias, mostly try to follow the URI

clip_image010

Click OK on the next screen

clip_image012

XML Structure taskpane will be visible

clip_image014

Add the Document into the Word file by clicking on it, you will see the tags on the Word File

clip_image016

Add a table in between the Document tags as below, key in the field name also

clip_image018

Place cursor in the cell beside the Supplier cell, then click on Supplier at the XML Structure task pane.

clip_image020

You now can see the Supplier tags

clip_image022

Do the same for the rest of the elements

clip_image024

Between each tag put a space as a placeholder, Word at the backend will create a <w:t> element

clip_image026

You can now save and close the Word document

Open up Visual Studio

Now we want to write a program to inject value into the 4 elements defined in the document above, which are:

1. Supplier

2. Phone

3. Fax

4. AttentionTo

Create a console application, name it DocGenWithXmlSchema

clip_image028

Add reference to the libraries I want to use, they are DocumentFormat.OpenXml (OpenXML SDK),

clip_image030

All the main method of program.cs, define the XMLNamespace

clip_image032

If you didn’t add the Using statement, you can use the resolve context menu to do it. (C# only)

clip_image034

Create variable to hold the filename

clip_image036

Add a using block to open the Word document

clip_image038

Instantiate the MainDocumentPart and read it into XDocument

clip_image040

Then take out all the XElements of “w:customXml” which are the XML Schema Tag we put in the Word document. Use foreach to loop thru the elements

clip_image042

Insert a switch-case block within the foreach block

clip_image044

Since I know which values in the 4 tags I want to replace, I use case to find the tagname and replace the value

clip_image046

After the foreach block, save the document

clip_image048

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>