This documentation is archived and is not being maintained.

XmlDsigXsltTransform Class

Represents the XSLT transform for a digital signature as defined by the W3C.

Namespace:  System.Security.Cryptography.Xml
Assembly:  System.Security (in System.Security.dll)

public class XmlDsigXsltTransform : Transform

The XmlDsigXPathTransform class allows you to address an XML document using an XSLT transformation. This class uses XSLT to transform XML nodes into other XML nodes that you want to sign or encrypt.

Use the XmlDsigXsltTransform class to sign or encrypt specific parts of an XML document using an XSLT transformation.

The Uniform Resource Identifier (URI) that describes the XmlDsigXsltTransform class is defined by the XmlDsigXsltTransformUrl field.

For more information about the XSLT transform, see Section 6.6.5 of the XMLDSIG specification, which is available from the W3C at

This section contains two code examples. The first code example shows how to sign and verify an XML document using the XmlDsigXsltTransform class with an envelope signature. The second code example demonstrates how to use members of the XmlDsigXsltTransform class.

Example #1

// This example signs an XML file using an 
// envelope signature. It then verifies the  
// signed XML. 
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;

public class SignVerifyEnvelope

    public static void Main(String[] args)
        // Generate a signing key.
        RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

        string xsl = @"
    <xs:transform xmlns:xs='' version='1.0'>
        <xs:template match='/'>
        <xs:template match='ElementToTransform'> 

            // Create an XML file to sign.
            Console.WriteLine("New XML file created.");

            // Sign the XML that was just created and save it in a  
            // new file.
            SignXmlFile("Example.xml", "SignedExample.xml", Key, xsl);
            Console.WriteLine("XML file signed.");

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");
            bool result = VerifyXmlFile("SignedExample.xml");

            // Display the results of the signature verification to \ 
            // the console. 
            if (result)
                Console.WriteLine("The XML signature is valid.");
                Console.WriteLine("The XML signature is not valid.");
        catch (CryptographicException e)


    // Sign an XML file and save the signature in a new file. 
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string XSLString)
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document. 
        signedXml.SigningKey = Key;

        // Create a reference to be signed.
        Reference reference = new Reference();
        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

        // Create an XmlDsigXPathTransform object using  
        // the helper method 'CreateXPathTransform' defined 
        // later in this sample.

        XmlDsigXsltTransform XsltTransform = CreateXsltTransform(XSLString);

        // Add the transform to the reference.

        // Add the reference to the SignedXml object.

        // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new RSAKeyValue((RSA)Key));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.

        // Get the XML representation of the signature and save 
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        // Save the signed XML document to a file specified 
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
    // Verify the signature of an XML file and return the result. 
    public static Boolean VerifyXmlFile(String Name)
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();

        // Format using white spaces.
        xmlDocument.PreserveWhitespace = true;

        // Load the passed XML file into the document. 

        // Create a new SignedXml object and pass it 
        // the XML document class.
        SignedXml signedXml = new SignedXml(xmlDocument);

        // Find the "Signature" node and create a new 
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

        // Load the signature node.

        // Check the signature and return the result. 
        return signedXml.CheckSignature();


    // Create the XML that represents the transform. 
    public static XmlDsigXsltTransform CreateXsltTransform(string xsl)
        XmlDocument doc = new XmlDocument();

        XmlDsigXsltTransform xform = new XmlDsigXsltTransform();

        return xform;

    // Create example data to sign. 
    public static void CreateSomeXml(string FileName)
        // Create a new XmlDocument object.
        XmlDocument document = new XmlDocument();

        // Create a new XmlNode object.
        XmlNode node = document.CreateNode(XmlNodeType.Element, "", "MyXML", "Don't_Sign");

        // Append the node to the document.

        // Create a new XmlNode object.
        XmlNode subnode = document.CreateNode(XmlNodeType.Element, "", "ElementToTransform", "Sign");

        // Add some text to the node.
        subnode.InnerText = "Here is some data to sign.";

        // Append the node to the document.

        // Save the XML document to the file name specified.
        XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));

Example #2

using System;
using System.IO;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Text;

class Class1
    static void Main(string[] args)
        XmlDocument productsXml = LoadProducts();
        XmlNodeList xsltNodeList = GetXsltAsNodeList();
        TransformDoc(productsXml, xsltNodeList);

        // Use XmlDsigXsltTransform to resolve a Uri.
        Uri baseUri = new Uri("");
        string relativeUri = "xml";
        Uri absoluteUri = ResolveUris(baseUri, relativeUri);

        Console.WriteLine("This sample completed successfully; " +
            "press Enter to exit.");

    private static void TransformDoc(
        XmlDocument xmlDoc, 
        XmlNodeList xsltNodeList)
            // Construct a new XmlDsigXsltTransform.
            XmlDsigXsltTransform xmlTransform = 
                new XmlDsigXsltTransform();

            // Load the Xslt tranform as a node list.

            // Load the Xml document to perform the tranform on.
            XmlNamespaceManager namespaceManager;
            namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);

            XmlNodeList productsNodeList;
            productsNodeList = xmlDoc.SelectNodes("//.", namespaceManager);


            // Retrieve the output from the transform.
            Stream outputStream = (Stream)

            // Read the output stream into a stream reader.
            StreamReader streamReader =
                new StreamReader(outputStream);

            // Read the stream into a string.
            string outputMessage = streamReader.ReadToEnd();

            // Close the streams.

            // Display to the console the Xml before and after 
            // encryption.
            Console.WriteLine("\nResult of transformation: " + outputMessage);
        catch (Exception ex)
            Console.WriteLine("Caught exception in TransformDoc method: " + 

    private static XmlNodeList GetXsltAsNodeList()
        string transformXml = "<xsl:transform version='1.0' ";
        transformXml += "xmlns:xsl=''>";
        transformXml += "<xsl:template match='products'>";
        transformXml += "<table><tr><td>ProductId</td><td>Name</td></tr>";
        transformXml += "<xsl:apply-templates/></table></xsl:template>";
        transformXml += "<xsl:template match='product'><tr>";
        transformXml += "<xsl:apply-templates/></tr></xsl:template>";
        transformXml += "<xsl:template match='productid'><td>";
        transformXml += "<xsl:apply-templates/></td></xsl:template>";
        transformXml += "<xsl:template match='description'><td>";
        transformXml += "<xsl:apply-templates/></td></xsl:template>";
        transformXml += "</xsl:transform>";

        Console.WriteLine("\nCreated the following Xslt tranform:");

        XmlDocument xmlDoc = new XmlDocument();
        return xmlDoc.GetElementsByTagName("xsl:transform");

    // Encrypt the text in the specified XmlDocument. 
    private static void ShowTransformProperties(
        XmlDsigXsltTransform xmlTransform)
        string classDescription = xmlTransform.ToString();
        Console.WriteLine("\n** Summary for " + classDescription + " **");

        // Retrieve the XML representation of the current transform.
        XmlElement xmlInTransform = xmlTransform.GetXml();
        Console.WriteLine("Xml representation of the current transform:\n" +

        // Ensure the transform is using the proper algorithm.
        xmlTransform.Algorithm =
        Console.WriteLine("Algorithm used: " + classDescription);

        // Retrieve the valid input types for the current transform.
        Type[] validInTypes = xmlTransform.InputTypes;
        Console.WriteLine("Transform accepts the following inputs:");
        for (int i=0; i<validInTypes.Length; i++)
            Console.WriteLine("\t" + validInTypes[i].ToString());

        Type[] validOutTypes = xmlTransform.OutputTypes;
        Console.WriteLine("Transform outputs in the following types:");
        for (int i=validOutTypes.Length-1; i >= 0; i--)
            Console.WriteLine("\t " + validOutTypes[i].ToString());

            if (validOutTypes[i] == typeof(object))
                object outputObject = xmlTransform.GetOutput();

    // Create an XML document describing various products. 
    private static XmlDocument LoadProducts()
        string contosoProducts = "<?xml version='1.0'?>";
        contosoProducts += "<products>";
        contosoProducts += "<product><productid>1</productid>";
        contosoProducts += "<description>Widgets</description></product>";
        contosoProducts += "<product><productid>2</productid>";
        contosoProducts += "<description>Gadgits</description></product>";
        contosoProducts += "</products>";

            "\nCreated the following Xml document for tranformation:");

        XmlDocument xmlDoc = new XmlDocument();
        return xmlDoc;

    // Resolve the specified base and relative Uri's . 
    private static Uri ResolveUris(Uri baseUri, string relativeUri)
        XmlUrlResolver xmlResolver = new XmlUrlResolver();
        xmlResolver.Credentials = 

        XmlDsigXsltTransform xmlTransform =
            new XmlDsigXsltTransform();
        xmlTransform.Resolver = xmlResolver;

        Uri absoluteUri = xmlResolver.ResolveUri(baseUri, relativeUri);
        if (absoluteUri != null)
                "\nResolved the base Uri and relative Uri to the following:");
                "Unable to resolve the base Uri and relative Uri");
        return absoluteUri;
// This sample produces the following output: 
// Created the following Xml document for tranformation: 
// <?xml version='1.0'?><products><product><productid>1</productid><descriptio 
// n>Widgets</description></product><product><productid>2</productid><descript 
// ion>Gadgits</description></product></products> 
// Created the following Xslt tranform: 
// <xsl:transform version='1.0' xmlns:xsl=' 
// m'><xsl:template match='products'><table><tr><td>ProductId</td><td>Name</td 
// ></tr><xsl:apply-templates/></table></xsl:template><xsl:template match='pro 
// duct'><tr><xsl:apply-templates/></tr></xsl:template><xsl:emplate match='pro 
// ductid'><td><xsl:apply-templates/></td></xsl:template><xsl:template match=' 
// description'><td><xsl:apply-templates/></td></xsl:template></xsl:transform> 
// Result of transformation: <table><tr><td>ProductId</td><td>Name</td></tr><t 
// r><td>1</td><td>Widgets</td></tr><tr><td>2</td><td>Gadgits</td></tr></table 
// > 
// ** Summary for System.Security.Cryptography.Xml.XmlDsigXsltTransform ** 
// Xml representation of the current transform: 
// <Transform Algorithm="" xmlns="h
// ttp://"><xsl:transform version="1.0" xmlns:xsl=" 
//"><xsl:template match="products"><table
//  xmlns=""><tr><td>ProductId</td><td>Name</td></tr><xsl:apply-templates /></
// table></xsl:template><xsl:template match="product"><tr xmlns=""><xsl:apply-
// templates /></tr></xsl:template><xsl:template match="productid"><td xmlns="
// "><xsl:apply-templates /></td></xsl:template><xsl:template match="descripti
// on"><td xmlns=""><xsl:apply-templates /></td></xsl:template></xsl:transform
// ></Transform> 
// Algorithm used: System.Security.Cryptography.Xml.XmlDsigXsltTransform 
// Transform accepts the following inputs: 
// System.IO.Stream 
// System.Xml.XmlDocument 
// System.Xml.XmlNodeList 
// Transform outputs in the following types: 
// System.IO.Stream 
// Resolved the base Uri and relative Uri to the following: 
// This sample completed successfully; press Enter to exit.


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0