15.12. Extending Transformations

Problem

You want to perform operations that are outside the scope of the transformation technology to include data in the transformed result.

Solution

If you are using LINQ to XML, you can call out to a function directly when transforming the result set, as shown here by the call to GetErrata:

	XElement publications = XElement.Load(@"..\..\publications.xml");
	XElement transformedPublications =
	    new XElement("PublishedWorks",
	        from b in publications.Elements("Book")
	        select new XElement(b.Name,
	                   new XAttribute(b.Attribute("name")),
	                   from c in b.Elements("Chapter")
	                   select new XElement("Chapter", GetErrata(c))));
	Console.WriteLine(transformedPublications.ToString( ));
	Console.WriteLine( );

The GetErrata method used in the above sample is listed here:

	private static XElement GetErrata(XElement chapter)
	{
	    // In here, we could go do other lookup calls (XML, database, web service)
	    // to get information to add back in to the transformation result
	    string errata = string.Format("{0} has {1} errata",
	                              chapter.Value, chapter.Value.Length);
	    return new XElement("Errata", errata);
	}

If you are using XSLT, you can add an extension object to the transformation that can perform the operations necessary based on the node it is passed. This can be accomplished by using the XsltArgumentList.AddExtensionObject method. This object you've created (XslExtensionObject) can then be accessed in the XSLT and a method called on it to return the data you want included in the final transformed ...

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.