Creating Word Documents with XSLT

来源:互联网 发布:js object 数组 编辑:程序博客网 时间:2024/06/04 01:23

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 

原创粉丝点击