15.14. Passing Parameters to Transformations
Problem
You need to transform some data using a mostly common pattern. For the few data items that could change between transformations, you don't want to have a separate mechanism for each variation.
Solution
If you are using LINQ to XML, simply build a method to encapsulate the transformation code and pass parameters to the method just as you normally would for other code:
// transform using LINQ instead of XSLT string storeTitle = "Hero Comics Inventory"; string pageDate = DateTime.Now.ToString("F"); XElement parameterExample = XElement.Load(@"..\..\ParameterExample.xml"); string htmlPath = @"..\..\ParameterExample_LINQ.htm"; TransformWithParameters(storeTitle, pageDate, parameterExample, htmlPath); // now change the parameters storeTitle = "Fabulous Adventures Inventory"; pageDate = DateTime.Now.ToString("D"); htmlPath = @"..\..\ParameterExample2_LINQ.htm"; TransformWithParameters(storeTitle, pageDate, parameterExample, htmlPath);
The TransformWithParameters
method looks like this:
private static void TransformWithParameters(string storeTitle, string pageDate, XElement parameterExample, string htmlPath) { XElement transformedParameterExample = new XElement("html", new XElement("head"), new XElement("body", new XElement("h3", string.Format("Brought to you by {0} on {1}{2}", storeTitle,pageDate,Environment.NewLine)), new XElement("br"), new XElement("table", new XAttribute("border","2"), new XElement("thead", new XElement("tr", new XElement("td", ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.