Share via


Controlling Output Format with the media-type Attribute

 

XSLT uses the <xsl:output> element to determine whether the output produced by the transformation is conformant XML (<xsl:output method="xml"/>), valid HTML (<xsl:output method="html"/>), or unverified text (<xsl:output method="text"/>). However, this can cause versioning problems, especially on the server, because Microsoft® Internet Information Services (IIS) automatically sets the output of ASP files to a mime-type of text/html to ensure that the browser interprets material sent to it as Web pages.

Although these types can determine the necessary headers, if any, the fact that a document is in XML format does not necessarily identify its output type. For example, a graphic file might be in Scalable Vector Graphics format, or a Wireless message might be in WML format. These files must inform ASP that they are both of type XML and have the appropriate mime-type (such as image/svg for SVG or text/vnd.wap.wml for WML).

The <xsl:output> command includes one additional attribute: media-type. This attribute is not used directly by the XSLT parser in generating output, but it can be read from the style sheet through the DOM, and used to set the Response.ContentType property. ContentType creates a header in the returning HTTP message. This header tells the browser how it should handle given mime-types. The following style sheet is an example.

<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" media-type="text/vnd.wap.wml"/>

<xsl:template match="/"/>

</xsl:stylesheet>

In this example, the media-type attribute has a value of "text/vnd.wap.wml". This indicates that the output from the style sheet should be a WML document. The getMimeType()function takes an XSLT processor object, and retrieves the mimeType from the <xsl:output> node. The full code for this example is in catalog.asp, in Sample ASP Script for XSLT Processor Objects.

function getMimeType(processor){
    var stylesheet=processor.stylesheet;
    var localTypeNode=stylesheet.selectSingleNode("//xsl:output/@media-type");
    if (""+localTypeNode=="undefined"){
        var localMethodNode=stylesheet.selectSingleNode("//xsl:output/@method");
        if (""+localMethodNode =="undefined"){
            mimeType="text/html";
            }
        else {
            localMethodName=localMethodNode.text;
            switch(localMethodName){
                case "text":mimeType="text/plain";break;
                case "html":mimeType="text/html";break;
                case "xml":mimeType="text/xml";break;
                }
            }
        }
    else {
        mimeType=localTypeNode.text;
        }
    return mimeType;
    }

You can then set the ContentType property by assigning the result of the getMimeType function to it, as follows:

Response.ContentType=getMimeType(processor)