(Update: June 23, 2008: I've updated and improved on this technique in this blog post)
I've received some comments indicating that XSLT is better for these types of transformations. FWIW, I absolutely agree about the usage scenarios for XSLT. In the LINQ to XML documentation, I have at least 4 or 5 examples that show how to use XSLT to transform an XML tree. XSLT transforms create a new tree, so XSLT does not aleviate the problems of too many short-lived objects.
With respect to processor cost, I haven't done any metrics, however, when doing XSLT transforms using LINQ to XML, the XML tree has to be transformed into an XPathDocument internally, which is a big transform. Then XPath expressions have to be evaluated, and then the transform is effected. In contrast, the LINQ to XML queries that you use to add annotations are quite efficient (due to lazy evaluation of LINQ queries and the semantics of LINQ to XML axes), and adding annotations is cheap. I am going to bet that the pure LINQ to XML approach is more efficient. However, I'm not going to test this until my current deadlines are met 🙂
One more note: this technique can expanded significantly. Possible improvements are:
- add modes, ala XSLT. Annotations are marked with modes. ApplyTransforms takes a mode as an attribute. The XForm function can also take a mode.
- allow for annotations on other types of nodes: attributes, text nodes, (and processing instructions and comments for completeness).
My only point about this post is that this is simply one approach to transforming XML trees when using LINQ to XML. It may be useful in some scenarios, but in other scenarios, XSLT may certainly be better.