XsltArgumentList para parâmetros de folha de estilos e objetos de extensãoXsltArgumentList for Style Sheet Parameters and Extension Objects

A classe de XsltArgumentList contém o idioma extensível de folha de estilos para objetos de parâmetros de transformações (XSLT) e a extensão XSLT.The XsltArgumentList class contains Extensible Stylesheet Language for Transformations (XSLT) parameters and XSLT extension objects. Quando passados para o método de Transform , esses parâmetros e objetos de extensão podem ser chamados de folhas de estilos.When passed into the Transform method, these parameters and extension objects can be invoked from style sheets.

Observação

As classes XslTransform e XsltArgumentList estão obsoletas no .NET Framework 2.0.The XslTransform and XsltArgumentList classes are obsolete in the .NET Framework 2.0. Você pode realizar transformações XSLT usando a classe de XslCompiledTransform .You can perform XSLT transformations using the XslCompiledTransform class. Confira Usar a classe XslCompiledTransform e Migrar da classe XslTransform para saber mais.See Using the XslCompiledTransform Class and Migrating From the XslTransform Class for more information.

A classe de XsltArgumentList contém objetos de parâmetros XSLT e de extensão XSLT.The XsltArgumentList class contains XSLT parameters and XSLT extension objects. Quando passados para o método de Transform , esses parâmetros e objetos de extensão podem ser chamados de folhas de estilos.When passed into the Transform method, these parameters and extension objects can be invoked from style sheets.

Os seguintes são vantagens de passar um objeto em vez de usar um script inserido:The following are advantages to passing an object rather than using an embedded script:

  • Fornece a melhor encapsulamento e reutilização de classes.Provides better encapsulation and reuse of classes.

  • Permite que as folhas de estilos são menores e mais sustentável.Allows style sheets to be smaller and more maintainable.

  • Suporte que chamam métodos nas classes que pertencem aos espaços para nomes diferentes de aquelas definidas dentro do conjunto de namespaces suporte de System .Supports calling methods on classes belonging to namespaces other than those defined within the set of supported System namespaces.

  • Suporte que passam partes da árvore de resultado à folha de estilos com o uso de XPathNodeIterator.Supports passing result tree fragments to the style sheet with the use of the XPathNodeIterator.

Parâmetros de folha de estilos XSLTXSLT Style Sheet Parameters

Os parâmetros XSLT são adicionados a XsltArgumentList usando o método AddParam .XSLT parameters are added to the XsltArgumentList using the AddParam method. Um nome qualificado e um namespace Uniform Resource Identifier (URI) são associados com o objeto de parâmetro no momento.A qualified name and namespace Uniform Resource Identifier (URI) are associated with the parameter object at that time.

O objeto de parâmetro deve corresponder a um tipo de World Wide Web Consortium (W3C).The parameter object should correspond to a World Wide Web Consortium (W3C) type. A tabela seguinte mostra tipos correspondentes W3C, as classes equivalentes do .NET Framework (tipo), e se o tipo W3C é um tipo de XPath (linguagem de caminho XML) ou tipo de XSLT.The following table shows the corresponding W3C types, the equivalent .NET Framework classes (type), and whether the W3C type is an XML Path Language (XPath) type or XSLT type.

Tipo W3CW3C Type Classe equivalente do .NET Framework (tipo)Equivalent .NET Framework class (type) Tipo XPath ou XSLTXPath type or XSLT type
StringString System.StringSystem.String XPathXPath
BooleanBoolean System.BooleanSystem.Boolean XPathXPath
NúmeroNumber System.DoubleSystem.Double XPathXPath
Fragmento da árvore de resultadoResult Tree Fragment System.Xml.XPath.XPathNavigatorSystem.Xml.XPath.XPathNavigator XSLTXSLT
Node SetNode Set System.Xml.XPath.XPathNodeIteratorSystem.Xml.XPath.XPathNodeIterator XPathXPath

Se o objeto de parâmetro não é uma das classes anterior, é forçado a um double ou para a cadeia de caracteres, como apropriado.If the parameter object is not one of the above classes, it is forced to either a Double or String, as appropriate. Int16, UInt16, Int32, UInt32, UInt64, Int64, e escolha os tipos decimais são forçados para um double.Int16, UInt16, Int32, UInt32, Int64, UInt64, Single and Decimal types are forced to a Double. Todos os outros tipos são forçados a uma cadeia de caracteres usando o método ToString .All other types are forced to a String using the ToString method.

Para usar o parâmetro XSLT, o usuário precisará fazer o seguinte:To use the XSLT parameter, the user needs to do the following:

  1. Crie XsltArgumentList e adicione os objetos usando AddParam.Create an XsltArgumentList and add the objects using AddParam.

  2. Chame os parâmetros de folha de estilos.Call the parameters from the style sheet.

  3. Passar XsltArgumentList para o método de Transform .Pass the XsltArgumentList to the Transform method.

ExemploExample

O exemplo a seguir usa o método de AddParam para criar um parâmetro para conter uma data calculada de desconto.The following example uses the AddParam method to create a parameter to hold a calculated discount date. A data de desconto é calculada para ser a 20 dias de data pedido.The discount date is calculated to be 20 days from the order date.

Imports System  
Imports System.IO  
Imports System.Xml  
Imports System.Xml.XPath  
Imports System.Xml.Xsl  
  
Public class Sample  
  
   Private Const filename As String = "order.xml"  
   Private Const stylesheet As String = "discount.xsl"  
  
   Public Shared Sub Main()  
  
    'Create the XslTransform and load the style sheet.  
    Dim xslt As XslTransform = New XslTransform  
    xslt.Load(stylesheet)  
  
    'Load the XML data file.  
    Dim doc As XPathDocument = New XPathDocument(filename)  
  
    'Create an XsltArgumentList.  
    Dim xslArg As XsltArgumentList = New XsltArgumentList  
  
    'Calculate the discount date.  
    Dim today As DateTime = DateTime.Now  
    Dim d As DateTime = today.AddDays(20)  
    xslArg.AddParam("discount", "", d.ToString())  
  
    'Create an XmlTextWriter to handle the output.  
    Dim writer As XmlTextWriter = New XmlTextWriter("orderout.xml", Nothing)  
  
    'Transform the file.  
    xslt.Transform(doc, xslArg, writer, Nothing)  
  
    writer.Close()  
  
  End Sub  
End Class  
using System;  
using System.IO;  
using System.Xml;  
using System.Xml.XPath;  
using System.Xml.Xsl;  
  
public class Sample  
{  
   private const String filename = "order.xml";  
   private const String stylesheet = "discount.xsl";  
  
   public static void Main() {  
  
    //Create the XslTransform and load the style sheet.  
    XslTransform xslt = new XslTransform();  
    xslt.Load(stylesheet);  
  
    //Load the XML data file.  
    XPathDocument doc = new XPathDocument(filename);  
  
    //Create an XsltArgumentList.  
    XsltArgumentList xslArg = new XsltArgumentList();  
  
    //Calculate the discount date.  
    DateTime today = DateTime.Now;  
    DateTime d = today.AddDays(20);  
    xslArg.AddParam("discount", "", d.ToString());  
  
    //Create an XmlTextWriter to handle the output.  
    XmlTextWriter writer = new XmlTextWriter("orderout.xml", null);  
  
    //Transform the file.  
    xslt.Transform(doc, xslArg, writer, null);  
    writer.Close();  
  }  
}  

EntradaInput

order.xmlorder.xml

<!--Represents a customer order-->  
<order>  
  <book ISBN='10-861003-324'>  
    <title>The Handmaid's Tale</title>  
    <price>19.95</price>  
  </book>  
  <cd ISBN='2-3631-4'>  
    <title>Americana</title>  
    <price>16.95</price>  
  </cd>  
</order>  

discount.xsldiscount.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  
  <xsl:param name="discount"/>  
  <xsl:template match="/">  
    <order>  
      <xsl:variable name="sub-total" select="sum(//price)"/>  
      <total><xsl:value-of select="$sub-total"/></total>  
      15% discount if paid by: <xsl:value-of select="$discount"/>  
    </order>  
  </xsl:template>  
</xsl:stylesheet>  

SaídaOutput

<order>  
   <total>36.9</total>
   15% discount if paid by: 5/6/2001 5:01:15 PM
</order>  

Objetos de extensão XSLTXSLT Extension Objects

Os objetos de extensão XSLT são adicionados a XsltArgumentList usando o método AddExtensionObject .XSLT extension objects are added to the XsltArgumentList using the AddExtensionObject method. Um nome qualificado e URI de namespace são associados com o objeto de extensão no momento.A qualified name and namespace URI are associated with the extension object at that time.

Quando um objeto é adicionado, o chamador de AddExtensionObject deve ser totalmente confiável na política de segurança.When an object is added, the caller of the AddExtensionObject must be fully trusted in the security policy. Se o chamador é de confiança parcial, a adição falhará.If the caller is semi-trusted, the addition will fail.

Um objeto é adicionado embora com êxito, ele não garante que a execução será com êxito.Though an object is added successfully, it does not guarantee that the execution will be successful. Quando o método de Transform é chamado, as permissões são calculadas com a evidência fornecida em tempo de Load , e esse conjunto de permissões é atribuído ao processo inteiro de transformação.When the Transform method is called, permissions are calculated against the evidence provided at Load time, and that permission set is assigned to the entire transformation process. Se um objeto de extensão tentar iniciar uma ação que requer permissões não encontradas no dataset, uma exceção é lançada.If an extension object attempts to initiate an action that requires permissions not found in the set, an exception is thrown.

Os tipos de dados retornados de objetos de extensão é um dos quatro tipos de dados básicos XPath número, cadeia de caracteres, conjunto booleano, e o nó.The data types returned from extension objects are one of the four basic XPath data types of number, string, Boolean, and node set.

Para usar o objeto de extensão XSLT, o usuário precisará fazer o seguinte:To use the XSLT extension object, the user needs to do the following:

  1. Crie XsltArgumentList e adicione o objeto de extensão usando AddExtensionObject.Create an XsltArgumentList and add the extension object using AddExtensionObject.

  2. Chamar o objeto de extensão folha de estilos.Invoke the extension object from the style sheet.

  3. Passar XsltArgumentList para o método de Transform .Pass the XsltArgumentList to the Transform method.

ExemploExample

O exemplo a seguir calcula a circunferência de um círculo determinado o raio.The following example calculates the circumference of a circle given its radius.

Imports System  
Imports System.IO  
Imports System.Xml  
Imports System.Xml.XPath  
Imports System.Xml.Xsl  
  
Public Class Sample  
   Private Const filename As String = "number.xml"  
   Private Const stylesheet As String = "circle.xsl"  
  
   Public Shared Sub Main()  
        Dim test As Sample = New Sample  
   End Sub  
  
  Public Sub New()  
    'Create the XslTransform and load the style sheet.  
    Dim xslt As XslTransform = New XslTransform  
    xslt.Load(stylesheet)  
  
    'Load the XML data file.  
    Dim doc As XPathDocument = New XPathDocument(filename)  
  
    'Create an XsltArgumentList.  
    Dim xslArg As XsltArgumentList = New XsltArgumentList  
  
    'Add an object to calculate the circumference of the circle.  
    Dim obj As Calculate = New Calculate  
    xslArg.AddExtensionObject("urn:myObj", obj)  
  
    'Create an XmlTextWriter to output to the console.  
    Dim writer As XmlTextWriter = New XmlTextWriter(Console.Out)  
  
    'Transform the file.  
    xslt.Transform(doc, xslArg, writer, Nothing)  
    writer.Close()  
  
  End Sub  
  
  'Calculates the circumference of a circle given the radius.  
  Public Class Calculate  
  
    Private circ As double = 0  
  
    Public Function Circumference(radius As Double) As Double  
       circ = Math.PI*2*radius  
       Return circ  
    End Function  
  End Class  
End Class  
using System;  
using System.IO;  
using System.Xml;  
using System.Xml.XPath;  
using System.Xml.Xsl;  
  
public class Sample  
{  
   private const String filename = "number.xml";  
   private const String stylesheet = "circle.xsl";  
  
   public static void Main() {  
  
        Sample test = new Sample();  
    }  
  
  public Sample() {  
  
    //Create the XslTransform and load the style sheet.  
    XslTransform xslt = new XslTransform();  
    xslt.Load(stylesheet);  
  
    //Load the XML data file.  
    XPathDocument doc = new XPathDocument(filename);  
  
    //Create an XsltArgumentList.  
    XsltArgumentList xslArg = new XsltArgumentList();  
  
    //Add an object to calculate the circumference of the circle.  
    Calculate obj = new Calculate();  
    xslArg.AddExtensionObject("urn:myObj", obj);  
  
    //Create an XmlTextWriter to output to the console.  
    XmlTextWriter writer = new XmlTextWriter(Console.Out);  
  
    //Transform the file.  
    xslt.Transform(doc, xslArg, writer, null);  
    writer.Close();  
  
  }  
  
  //Calculates the circumference of a circle given the radius.  
  public class Calculate {  
  
    private double circ = 0;  
  
    public double Circumference(double radius){  
       circ = Math.PI*2*radius;  
       return circ;  
    }  
  }  
}  

EntradaInput

number.xmlnumber.xml

<?xml version='1.0'?>  
<data>  
  <circle>  
    <radius>12</radius>  
  </circle>  
  <circle>  
    <radius>37.5</radius>  
  </circle>  
</data>

circle.xslcircle.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  
    xmlns:myObj="urn:myObj">  
  
  <xsl:template match="data">  
  <circles>  
  <xsl:for-each select="circle">  
    <circle>  
    <xsl:copy-of select="node()"/>  
       <circumference>  
          <xsl:value-of select="myObj:Circumference(radius)"/>
       </circumference>  
    </circle>  
  </xsl:for-each>  
  </circles>  
  </xsl:template>  
</xsl:stylesheet>  

SaídaOutput

<circles xmlns:myObj="urn:myObj">

<circle>

<radius>12</radius>

<circumference>75.398223686155</circumference>

</circle>

<circle>

<radius>37.5</radius>

<circumference>235.61944901923448</circumference>

</circle>

</circles>

Consulte tambémSee also