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)


<HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort := True)>
Public Class XmlDsigXsltTransform
	Inherits Transform


Initializes a new instance of the XmlDsigXsltTransform class.


Initializes a new instance of the XmlDsigXsltTransform class with comments, if specified.


Gets or sets the Uniform Resource Identifier (URI) that identifies the algorithm performed by the current transform.(Inherited from Transform.)


Gets or sets an XmlElement object that represents the document context under which the current Transform object is running. (Inherited from Transform.)


Gets an array of types that are valid inputs to the LoadInput method of the current XmlDsigXsltTransform object.(Overrides Transform.InputTypes.)


Gets an array of types that are possible outputs from the GetOutput methods of the current XmlDsigXsltTransform object.(Overrides Transform.OutputTypes.)


Gets or sets a Hashtable object that contains the namespaces that are propagated into the signature. (Inherited from Transform.)


Sets the current XmlResolver object.(Inherited from Transform.)


Determines whether the specified object is equal to the current object.(Inherited from Object.)


Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)


When overridden in a derived class, returns the digest associated with a Transform object. (Inherited from Transform.)


Serves as the default hash function. (Inherited from Object.)


Returns an XML representation of the parameters of the XmlDsigXsltTransform object that are suitable to be included as subelements of an XMLDSIG <Transform> element.(Overrides Transform.GetInnerXml().)


Returns the output of the current XmlDsigXsltTransform object.(Overrides Transform.GetOutput().)


Returns the output of the current XmlDsigXsltTransform object of type Stream.(Overrides Transform.GetOutput(Type).)


Gets the Type of the current instance.(Inherited from Object.)


Returns the XML representation of the current Transform object.(Inherited from Transform.)


Parses the specified XmlNodeList object as transform-specific content of a <Transform> element and configures the internal state of the current XmlDsigXsltTransform object to match the <Transform> element.(Overrides Transform.LoadInnerXml(XmlNodeList).)


Loads the specified input into the current XmlDsigXsltTransform object.(Overrides Transform.LoadInput(Object).)


Creates a shallow copy of the current Object.(Inherited from Object.)


Returns a string that represents the current object.(Inherited from Object.)

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 www.w3.org/TR/xmldsig-core/.

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.
Imports System
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography.Xml
Imports System.Text
Imports System.Xml

Module SignVerifyEnvelope

    Sub Main(ByVal args() As String)
        ' Generate a signing key.
        Dim Key As New RSACryptoServiceProvider()

        Dim xsl As String = "<xs:transform xmlns:xs='http://www.w3.org/1999/XSL/Transform' version='1.0'> <xs:template match='/'> <xs:apply-templates/> </xs:template> <xs:template match='ElementToTransform'> <transformedElement/> </xs:template> </xs:transform>"

            ' 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...")
            Dim result As Boolean = VerifyXmlFile("SignedExample.xml")

            ' Display the results of the signature verification to \
            ' the console.
            If result Then
                Console.WriteLine("The XML signature is valid.")
                Console.WriteLine("The XML signature is not valid.")
            End If
        Catch e As CryptographicException
        End Try

    End Sub

    ' Sign an XML file and save the signature in a new file.
    Sub SignXmlFile(ByVal FileName As String, ByVal SignedFileName As String, ByVal Key As RSA, ByVal XSLString As String)
        ' Create a new XML document.
        Dim doc As 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.
        Dim signedXml As New SignedXml(doc)

        ' Add the key to the SignedXml document. 
        signedXml.SigningKey = Key

        ' Create a reference to be signed.
        Dim reference As New Reference()
        reference.Uri = ""

        ' Add an enveloped transformation to the reference.
        Dim env As New XmlDsigEnvelopedSignatureTransform()

        ' Create an XmlDsigXPathTransform object using 
        ' the helper method 'CreateXPathTransform' defined
        ' later in this sample.
        Dim XsltTransform As XmlDsigXsltTransform = 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).
        Dim keyInfo As New KeyInfo()
        keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA)))
        signedXml.KeyInfo = keyInfo

        ' Compute the signature.

        ' Get the XML representation of the signature and save
        ' it to an XmlElement object.
        Dim xmlDigitalSignature As XmlElement = 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.
        Dim xmltw As New XmlTextWriter(SignedFileName, New UTF8Encoding(False))

    End Sub

    ' Verify the signature of an XML file and return the result.
    Function VerifyXmlFile(ByVal Name As String) As [Boolean]
        ' Create a new XML document.
        Dim xmlDocument As 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.
        Dim signedXml As New SignedXml(xmlDocument)

        ' Find the "Signature" node and create a new
        ' XmlNodeList object.
        Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature")

        ' Load the signature node.
        signedXml.LoadXml(CType(nodeList(0), XmlElement))

        ' Check the signature and return the result.
        Return signedXml.CheckSignature()

    End Function

    ' Create the XML that represents the transform.
    Function CreateXsltTransform(ByVal xsl As String) As XmlDsigXsltTransform
        Dim doc As New XmlDocument()

        Dim xform As New XmlDsigXsltTransform()

        Return xform

    End Function

    ' Create example data to sign.
    Sub CreateSomeXml(ByVal FileName As String)
        ' Create a new XmlDocument object.
        Dim document As New XmlDocument()

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

        ' Append the node to the document.

        ' Create a new XmlNode object.
        Dim subnode As XmlNode = 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.
        Dim xmltw As New XmlTextWriter(FileName, New UTF8Encoding(False))

    End Sub
End Module

Example #2

Imports System
Imports System.IO
Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml
Imports System.Text

Public Class Form1
    Inherits System.Windows.Forms.Form

    ' Event handler for Run button.
    Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        tbxOutput.Cursor = Cursors.WaitCursor
        tbxOutput.Text = ""

        Dim productsXml As XmlDocument = LoadProducts()
        Dim xsltNodeList As XmlNodeList = GetXsltAsNodeList()
        TransformDoc(productsXml, xsltNodeList)

        ' Use XmlDsigXsltTransform to resolve a Uri.
        Dim baseUri As New Uri("http://www.contoso.com")
        Dim relativeUri As String = "xml"
        Dim absoluteUri As Uri = ResolveUris(baseUri, relativeUri)

        ' Align interface and conclude application.
        WriteLine(vbCrLf + "This sample completed successfully;" + _
            " press Exit to continue.")

        ' Reset the cursor.
        tbxOutput.Cursor = Cursors.Default
    End Sub

    ' Create an XML document describing various products.
    Private Function LoadProducts() As XmlDocument
        Dim contosoProducts As String = "<?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>"

        WriteLine(vbCrLf + _
            "Created the following Xml document for tranformation:")

        Dim xmlDoc As New XmlDocument
        Return xmlDoc
    End Function

    Private Function GetXsltAsNodeList() As XmlNodeList
        Dim transformXml As String = "<xsl:transform version='1.0' "
        transformXml += "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>"
        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>"

        WriteLine(vbCrLf + "Created the following Xslt tranform:")

        Dim xmlDoc As New XmlDocument
        Return xmlDoc.GetElementsByTagName("xsl:transform")
    End Function

    Private Sub TransformDoc( _
        ByVal xmlDoc As XmlDocument, _
        ByVal xsltNodeList As XmlNodeList)

            ' Construct a new XmlDsigXsltTransform.
            Dim xmlTransform As New XmlDsigXsltTransform

            ' Load the Xslt tranform as a node list.

            ' Load the Xml document to perform the tranform on.
            dim namespaceManager as New XmlNamespaceManager(xmlDoc.NameTable)

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


            ' Retrieve the output from the transform.
            Dim outputStream As Stream
            outputStream = CType(xmlTransform.GetOutput( _
                GetType(System.IO.Stream)), _

            ' Read the output stream into a stream reader.
            Dim streamReader As New StreamReader(outputStream)

            ' Read the stream into a string.
            Dim outputMessage As String = streamReader.ReadToEnd()

            ' Close the streams.

            ' Display to the console the Xml before and after encryption.
            WriteLine(vbCrLf + "Result of transformation: " + outputMessage)
        Catch ex As Exception
            WriteLine("Caught exception in TransformDoc method: " + _
        End Try
    End Sub

    Private Sub ShowTransformProperties( _
            ByVal xmlTransform As XmlDsigXsltTransform)

        Dim classDescription As String = xmlTransform.ToString()
        WriteLine(vbCrLf + "** Summary for " + classDescription + " **")

        ' Retrieve the XML representation of the current transform.
        Dim xmlInTransform As XmlElement = xmlTransform.GetXml()
        WriteLine("Xml representation of the current transform:" + _
            vbCrLf + xmlInTransform.OuterXml)

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

        ' Retrieve the valid input types for the current transform.
        Dim validInTypes() As Type = xmlTransform.InputTypes
        WriteLine("Transform accepts the following inputs:")
        For i As Int16 = 0 To validInTypes.Length - 1 Step 1
            WriteLine("   " + validInTypes(i).ToString())

        Dim validOutTypes() As Type = xmlTransform.OutputTypes
        WriteLine("Transform outputs in the following types:")
        For j As Int16 = 0 To validOutTypes.Length - 1 Step 1

            WriteLine("   " + validOutTypes(j).ToString())
            If (validOutTypes(j).Equals(GetType(Object))) Then
                Dim outputObject As Object = xmlTransform.GetOutput()
            End If
    End Sub

    ' Resolve the specified base and relative Uri's .
    Private Function ResolveUris( _
        ByVal baseUri As Uri, _
        ByVal relativeUri As String) As Uri

        Dim xmlResolver As New XmlUrlResolver
        xmlResolver.Credentials = _

        Dim xmlTransform As New XmlDsigXsltTransform
        xmlTransform.Resolver = xmlResolver

        Dim absoluteUri As Uri = xmlResolver.ResolveUri(baseUri, relativeUri)
        If (Not absoluteUri Is Nothing) Then
            WriteLine(vbCrLf + _
                "Resolved the base Uri and relative Uri to the following:")
            WriteLine("Unable to resolve the base Uri and relative Uri")
        End If

        Return absoluteUri
    End Function

    ' Write specified message and carriage return to the output textbox.
    Private Sub WriteLine(ByVal message As String)
        tbxOutput.AppendText(message + vbCrLf)

    End Sub

    ' Event handler for Exit button.
    Private Sub Button2_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button2.Click

    End Sub
#Region " Windows Form Designer generated code "

    Public Sub New()

        'This call is required by the Windows Form Designer.

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
            End If
        End If
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Panel2 As System.Windows.Forms.Panel
    Friend WithEvents Panel1 As System.Windows.Forms.Panel
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button2 As System.Windows.Forms.Button
    Friend WithEvents tbxOutput As System.Windows.Forms.RichTextBox
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.Panel2 = New System.Windows.Forms.Panel
        Me.Button1 = New System.Windows.Forms.Button
        Me.Button2 = New System.Windows.Forms.Button
        Me.Panel1 = New System.Windows.Forms.Panel
        Me.tbxOutput = New System.Windows.Forms.RichTextBox
        Me.Panel2.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.Panel2.DockPadding.All = 20
        Me.Panel2.Location = New System.Drawing.Point(0, 320)
        Me.Panel2.Name = "Panel2"
        Me.Panel2.Size = New System.Drawing.Size(616, 64)
        Me.Panel2.TabIndex = 1
        Me.Button1.Dock = System.Windows.Forms.DockStyle.Right
        Me.Button1.Font = New System.Drawing.Font( _
            "Microsoft Sans Serif", _
            9.0!, _
            System.Drawing.FontStyle.Regular, _
            System.Drawing.GraphicsUnit.Point, _
            CType(0, Byte))
        Me.Button1.Location = New System.Drawing.Point(446, 20)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(75, 24)
        Me.Button1.TabIndex = 2
        Me.Button1.Text = "&Run"
        Me.Button2.Dock = System.Windows.Forms.DockStyle.Right
        Me.Button2.Font = New System.Drawing.Font( _
            "Microsoft Sans Serif", _
            9.0!, _
            System.Drawing.FontStyle.Regular, _
            System.Drawing.GraphicsUnit.Point, _
            CType(0, Byte))
        Me.Button2.Location = New System.Drawing.Point(521, 20)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(75, 24)
        Me.Button2.TabIndex = 3
        Me.Button2.Text = "E&xit"
        Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.Panel1.DockPadding.All = 20
        Me.Panel1.Location = New System.Drawing.Point(0, 0)
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Size = New System.Drawing.Size(616, 320)
        Me.Panel1.TabIndex = 2
        Me.tbxOutput.AccessibleDescription = _
            "Displays output from application."
        Me.tbxOutput.AccessibleName = "Output textbox."
        Me.tbxOutput.Dock = System.Windows.Forms.DockStyle.Fill
        Me.tbxOutput.Location = New System.Drawing.Point(20, 20)
        Me.tbxOutput.Name = "tbxOutput"
        Me.tbxOutput.Size = New System.Drawing.Size(576, 280)
        Me.tbxOutput.TabIndex = 1
        Me.tbxOutput.Text = "Click the Run button to run the application."
        Me.AutoScaleBaseSize = New System.Drawing.Size(6, 15)
        Me.ClientSize = New System.Drawing.Size(616, 384)
        Me.Name = "Form1"
        Me.Text = "XmlDsigXsltTransform"

    End Sub

#End Region
End Class
' This sample produces the following output:
' Created the following Xml document for tranformation:
' <?xml version='1.0'?><products><product><productid>1</productid><description
' >Widgets</description></product><product><productid>2</productid><descriptio
' n>Gadgits</description></product></products>
' Created the following Xslt tranform:
' <xsl:transform version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform
' '><xsl:template match='products'><table><tr><td>ProductId</td><td>Name</td><
' /tr><xsl:apply-templates/></table></xsl:template><xsl:template match='produc
' t'><tr><xsl:apply-templates/></tr></xsl:template><xsl:template match='produc
' tid'><td><xsl:apply-templates/></td></xsl:template><xsl:template match='desc
' ription'><td><xsl:apply-templates/></td></xsl:template></xsl:transform>
' Result of transformation: <table><tr><td>ProductId</td><td>Name</td></tr><tr
' ><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="http://www.w3.org/TR/1999/REC-xslt-19991116" xmlns="ht
' tp://www.w3.org/2000/09/xmldsig#"><xsl:transform version="1.0" xmlns:xsl="ht
' tp://www.w3.org/1999/XSL/Transform"><xsl:template match="products"><table xm
' lns=""><tr><td>ProductId</td><td>Name</td></tr><xsl:apply-templates /></tabl
' e></xsl:template><xsl:template match="product"><tr xmlns=""><xsl:apply-templ
' ates /></tr></xsl:template><xsl:template match="productid"><td xmlns=""><xsl
' :apply-templates /></td></xsl:template><xsl:template match="description"><td
'  xmlns=""><xsl:apply-templates /></td></xsl:template></xsl:transform></Trans
' form>
' 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:
' http://www.contoso.com/xml
' This sample completed successfully; press Exit to continue.

.NET Framework
Available since 1.1

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

Return to top