Creating Word Documents with XSLT

Creating Word Documents with XSLT

Using the Office Schemas it is easy to create Microsoft Word 2003 documents.

Let's start with this XML document:

<?xml version="1.0" encoding="utf-8" ?>
<Courses>
 <Course Number="MS-2524">
  <Title>XML Web Services Programming</Title>
 </Course>
 <Course Number="MS-2124">
  <Title>C# Programming</Title>
 </Course>
 <Course Number="NET2">
  <Title>.NET 2.0 Early Adapter</Title>
 </Course>
</Courses>

The result should be a Word document.

A simple Word document containing the above data can be as simple as this:

<?xml version="1.0" encoding="utf-8"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument xmlns:w="
http://schemas.microsoft.com/office/word/2003/wordml">
  <w:body>
    <w:p>
      <w:r>
        <w:t>MS-2524, XML Web Services Programming</w:t>
      </w:r>
    </w:p>
    <w:p>
      <w:r>
        <w:t>MS-2124, C# Programming</w:t>
      </w:r>
    </w:p>
    <w:p>
      <w:r>
        <w:t>NET2, .NET 2.0 Early Adapter</w:t>
      </w:r>
    </w:p>
  </w:body>
</w:wordDocument>

With XSLT the document can be created using this style sheet:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="
http://www.w3.org/1999/XSL/Transform"
 xmlns:w="
http://schemas.microsoft.com/office/word/2003/wordml">
 <xsl:output method="xml" indent="yes" />
 <xsl:template match="/">
  <xsl:processing-instruction name="mso-application">
   <xsl:text>progid="Word.Document"</xsl:text>
  </xsl:processing-instruction>
  <w:wordDocument>
   <w:body>
     <xsl:apply-templates select="Courses/Course" />
   </w:body>
  </w:wordDocument>
 </xsl:template>
 <xsl:template match="Course">
    <w:p>
     <w:r>
      <w:t>
       <xsl:value-of select="@Number" />, <xsl:value-of select="Title"/>
      </w:t>
     </w:r>
    </w:p>
 </xsl:template>
</xsl:stylesheet>

Adding the processing instruction mso-application to the document allows the system to deal with the XML file as a Word document. The parser reads the progid for Word to display the Word icon, and to start Word when opening the file.

  <xsl:processing-instruction name="mso-application">
   <xsl:text>progid="Word.Document"</xsl:text>
  </xsl:processing-instruction>

The elements <w:wordDocument> and <w:body> can be compared to the HTML tags <HTML> and <BODY>. <w:t> is the tag for a text output.

The schemas for Microsoft Office 2003 can be downloaded from the MSDN Website. The download is an installation package that includes schemas for Office 2003 as well as documentation. Referencing the schemas with the XML and XSLT editors of Visual Studio 2005 gives intellisense :-)

Christian 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值