Sunday, November 30, 2003 4:15 PM
bart
Generating Word documents with XML and XSLT
For the SchoolServer project I needed to create Word documents which contain the login, initial password and root folder for each student, teacher and staff member (mail merge). Thanks to Office 2003 and the support for XML in Word it's now possible to create Word 2003 documents by transforming and XML data source (i.e. a DataSet object) using and XSLT stylesheet to a Word document. Really cool! Let's post some code:
XmlDocument doc=
new XmlDataDocument(persons);
XslTransform students = new XslTransform();
students.Load(dir + "students.xsl");
XmlWriter oStudents = new XmlTextWriter(dir + "\\students.xml",Encoding.Default);
Transform(students,doc,oStudents);
oStudents.Close();
In here, the persons object is a dataset which contains all the data of the students. The output document is students.xml (dir is just the output directory of the mail merge), so it has the extension .xml instead of .doc. Now, how does the system know it's a word document? This is specified in the first part of the XSLT file:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml" >
< xsl:template match="/" >
< xsl:processing-instruction name="mso-application">progid="Word.Document"< / xsl:processing-instruction >
< w:wordDocument xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:sl="http://schemas.microsoft.com/schemaLibrary/2003/core" xmlns:aml="http://schemas.microsoft.com/aml/2001/core" xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" w:macrosPresent="no" w:embeddedObjPresent="no" w:ocxPresent="no" xml:space="preserve" >
< w:docPr >
< w:view w:val="print" / >
< / w:docPr >
< w:body >
< wx:sect >
< xsl:apply-templates / >
< / wx:sect >
< / w:body >
< / w:wordDocument >
< / xsl:template >
The xsl:processing-instruction part does the trick. This value is read by the Windows shell to determine the associated program for the xml file type. Of course your primary question is how to find this XML code with the , , magic tags? Well, that's very easy: open Word 2003 and save the document as an XML document. The only thing left you need to do is to create an XSLT file based on the generated XML file.
Welcome in the world of WordML! Enjoy it...
?>
Del.icio.us |
Digg It |
Technorati |
Blinklist |
Furl |
reddit |
DotNetKicks
Filed under: Microsoft