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
Open up Word 2007, click on Schema
Click on Add Schema
Select the schema you created just now in file dialog
Enter an alias, mostly try to follow the URI
Click OK on the next screen
XML Structure taskpane will be visible
Add the Document into the Word file by clicking on it, you will see the tags on the Word File
Add a table in between the Document tags as below, key in the field name also
Place cursor in the cell beside the Supplier cell, then click on Supplier at the XML Structure task pane.
You now can see the Supplier tags
Do the same for the rest of the elements
Between each tag put a space as a placeholder, Word at the backend will create a <w:t> element
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
Add reference to the libraries I want to use, they are DocumentFormat.OpenXml (OpenXML SDK),
All the main method of program.cs, define the XMLNamespace
If you didn’t add the Using statement, you can use the resolve context menu to do it. (C# only)
Create variable to hold the filename
Add a using block to open the Word document
Instantiate the MainDocumentPart and read it into XDocument
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
Insert a switch-case block within the foreach block
Since I know which values in the 4 tags I want to replace, I use case to find the tagname and replace the value
After the foreach block, save the document