Sunday, July 7, 2013

Razor vs. XSLT

Razor and XSLT are both excellent tools. The following table compares their strengths and weaknesses, you decide which capabilities are most important for your particular scenario. Feedback is welcome, and I intend to update this table as both languages evolve.

Capability Razor XSLT
Process XML (or normalized HTML) Requires external component like DOM or LINQ to XML, or conversion to objects XPath
Process objects C# or VB Requires conversion to in-memory representation (e.g. DOM), data only, no functions
Modularity File-based. In App_Code, directories map to namespaces, files to classes and helpers to methods. URI-based (XmlResolver extensibility), stylesheets, templates (modes), namespaces (QNames)
Inheritance Layouts, start pages (_PageStart, _ViewStart) xsl:import
Template overriding Abstract sections Template precedence, xsl:next-match in v2, xsl:apply-imports in v1
Dynamic invoke RenderPage/RenderPartial Must import module (some processors have extensions)
Processing styles Pull. ASP.NET MVC has some push support with Html.EditorFor and Html.DisplayFor. Push and pull
Post-process output (multi-step, chaining) Not supported v2 or exsl:node-set in v1
Type system .NET, static and dynamic v1 has 5 data types: String, number, boolean, node-set and result tree fragment.
v2 has sequences and 20+ atomic types. Complex types and PSVI requires schema-awareness (XML Schema).
Function library Everything .NET Limited but extensible
Delegated templates e.g. Func<dynamic, object> b = @<strong>@item</strong>; Template reference technique
Serialization HTML (default encoding). RazorEngine library provides encoding extensibility. XML, HTML, XHTML and text. Indentation and whitespace control. XmlWriter extensibility.
Framework integration ASP.NET MVC: Display and editor templates, data annotations attribute-based validation, URL generation. Not available
Portability .NET and Mono Available in many frameworks, languages, operating systems and browsers

XSLT tools for .NET/Visual Studio

Further Reading

2 comments:

  1. Did you do any performance/benchmark comparisons between the two? Would be curious to see that.

    ReplyDelete
    Replies
    1. No, for various reasons:

      1. XSLT performance depends on the processor, and this article is about the languages and not any particular implementation.

      2. If you choose one over the other it would be to do something that the other cannot do, e.g. multi-step processing in XSLT, since there's no equivalent in Razor there's no way to compare the two.

      3. Razor is a lot simpler than XSLT, since it's basically a pre-processor that turns markup into TextWriter calls. XSLT implementations, on the other hand, have been around longer. Processors like XslCompiledTransform or Saxon-EE compile directly to IL. From my experience in "real world" projects, XSLT is as fast as Razor, so a performance comparison is not interesting to me.

      Delete