Transforming XML Data Using Functional Construction
Functional construction is quite literally a way to create an XML tree in a single statement by chaining function calls together where subordinate calls are arguments to the calling method. (This same nesting of method calls is also often used in the CodeDOM namespace to create code graphs.)
The XML document in Listing One was created with functional construction. Quite straightforward really, the XML tree was created by chaining XElement (and XAttribute) objects together to form the shape of the XML document and calling the XElement.Save method.
private void SerializeGameStatistics(BlackJack game) { try { Statistics stats = game.Players[0].Statistics; //serialize game to XML XElement xml = new XElement("Blackjack", new XElement("Player", new XAttribute("Name", game.Players[0].Name), new XElement("Statistics", new XElement("AverageAmountLost", stats.AverageAmountLost), new XElement("AverageAmountWon", stats.AverageAmountWon), new XElement("Blackjacks", stats.BlackJacks), new XElement("Losses", stats.Losses), new XElement("NetAverageWinLoss", stats.NetAverageWinLoss), new XElement("NewWinLoss", stats.NetWinLoss), new XElement("PercentageOfBlackJacks", stats.PercentageOfBlackJacks), new XElement("PercentageOfLosses", stats.PercentageOfLosses), new XElement("PercentageOfPushes", stats.PercentageOfPushes), new XElement("PercentageOfWins", stats.PercentageOfWins), new XElement("Pushes", stats.Pushes), new XElement("Surrenders", stats.Surrenders), new XElement("TotalAmountLost", stats.TotalAmountLost), new XElement("TotalAmountWon", stats.TotalAmountWon), new XElement("Wins", stats.Wins)))); xml.Save( Path.GetDirectoryName( Application.ExecutablePath) + "\\CurrentStats.xml"); } catch{} }
The method in Listing Seven was added to the Blackjack sample application. The data is derived from objects in that game, but the orchestration of the XElement objects could really be applied to any objects.
Summary
XPath is an open standard for querying and transforming XML documents; however, it is a completely different technology than C# programming, which you already know. With LINQ-to-XML, you can now do some of the things provided by XPath in a way you already know how to do them.
Rough Cuts is a Safari Books Online interactive publishing service that provides you with first access to pre-published manuscripts on hot technology topics-enabling you to stay on the cutting-edge and remain competitive. This version may not be final, the published book will be available in August 2008.