You can think of an extension object as an external class that can be referenced and used within an XSL style sheet. Because of its powerful nature, extension objects can go a long way in increasing the func- tionality of style sheets. Extension objects are maintained by the XsltArgumentList class. The follow- ing are advantages to using an extension object rather than embedded script: |
Provides better encapsulation and reuse of classes |
Allows style sheets to be smaller and more maintainable |
XSLT extension objects are added to the XsltArgumentList object using the AddExtensionObject() |
method. Aqualified name and namespace URI are associated with the extension object at that time. To use an extension object, you need to go through the following steps: |
1. Create an XsltArgumentList object and add the extension object to the XsltArgumentList |
object using AddExtensionObject() method |
2. Pass the XsltArgumentList object to the Transform() method |
3. Call the extension object’s methods from the style sheet |
To see how this works in practice, the next code sample shown in Listing 7-8 replaces the parameter driven approach used (see Listing 7-5) for calculating the discount with the extension object-based approach. The next section demonstrates the code of the extension class that is used to calculate the discount. |
Declaration of the Extension Class |
Before looking at the XSL style sheet, take a look at the declaration of the Discount class shown in Listing 7-7. When creating the Discount class through Visual Studio, remember to place the class in the |
App_Code directory by saying “Yes” to the prompt that asks if you want to place the class in the |
App_Code directory. Placing the class in the App_Code directory ensures that the Discount class is auto- matically available to all the Web pages contained within the same virtual directory. |
Listing 7-7: Declaration of the Discount Class |
public class Discount { |
public Discount() { } public string ReturnDiscount(string price) { |
decimal priceValue = Convert.ToDecimal(price); return (priceValue * 15/100).ToString(); |
} |
} |
The Discount class contains only one method, named ReturnDiscount(), that calculates the discount and returns the calculated discount to the caller. Since the ReturnDiscount() method contains the necessary code to calculate the discount, the XSLT style sheet obviously needs to be able to reference the Discount |
object that is passed in and call its ReturnDiscount() method. This is accomplished by adding the proper namespace prefix and URI into the style sheet. Listing 7-8 shows the complete style sheet with the declara- tion of the namespace and shows how the ReturnDiscount() method is invoked. |
learn guitarphysics learnteliphonyxmlphysicsenjoylife