Well, here is a small basic example how to generate WordprocessingML documents basing on templates. Saying "template" I don't mean regular *.dot Word templates, but just WordprocessingML XML document with predefined document/paragraph/run level properties and styles. Having such template document basically all needs to be done is to fill it with real content.
Here is such a template, it's empty Word 2003 document where I defined new style called MyFancyStyle and saved document as XML.
Here is the source of the content - a hypothetical report:
<?xml version="1.0"> <report><link url="http://www.internettrafficreport.com/main.htm">Internet Traffic Report</link> reports on the current performance of major Internet routes around the world.</report>
And here goes XSLT stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint" xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml"> <xsl:variable name="root" select="/*"/> <xsl:template match="/"> <xsl:apply-templates select="document('d:\temp\WordTemplate.xml')/node()" mode="template"/> </xsl:template> <xsl:template match="@*|node()" mode="template"> <xsl:copy> <xsl:apply-templates select="@*|node()" mode="template"/> </xsl:copy> </xsl:template> <xsl:template match="w:body/wx:sect" mode="template"> <xsl:copy> <xsl:apply-templates select="$root"/> <xsl:copy-of select="wx:sectPr"/> </xsl:copy> </xsl:template> <xsl:template match="report"> <w:p> <w:pPr> <w:pStyle w:val="MyFancyStyle"/> </w:pPr> <xsl:apply-templates/> </w:p> </xsl:template> <xsl:template match="text()"> <w:r> <w:t><xsl:value-of select="."/></w:t> </w:r> </xsl:template> <xsl:template match="link"> <w:hlink w:dest="{@url}"> <w:r> <w:rPr> <w:rStyle w:val="Hyperlink"/> </w:rPr> <xsl:apply-templates/> </w:r> </w:hlink> </xsl:template> </xsl:stylesheet>Basically what the stylesheet does? It opens template document, recursively copies all its content till it reaches w:body/wx:sect element. That's considered to be entry point for the content. Then stylesheet runs usual processing of the actual content in the source document, applying MyFancyStyle to the paragraph and after that copies wx:sectPr. Not rocket engineering indeed.
And finally here is how the result looks like. Note, real content is styled by MyFancyStyle style defined in the template.
Leave a comment