Home - nootn/RazorEngineFromXml GitHub Wiki

About

This library was built to be used as an alternative to XSLT.

Using Razor in some situations might be "cleaner" than XSLT as you can perform Linq queries instead of XPath queries. It is also more fun writing C# than XPath :)

Check out the implemented requirements for what it can do.

Getting Started

  1. Create a new application, this example will use a C# Console Application.

  2. Install the NuGet package http://www.nuget.org/packages/RazorEngineFromXml

  3. Instantiate a "TemplateServiceXml" object

  4. Get the Razor Template to use for the transform as a string

  5. Get the XML to use for the transform as a string

  6. Call "Parse" on the service passing the two strings

  7. The result you get will be the transformed string

     //C# example
     using System;
     using RazorEngineFromXml;
     namespace NuGetTest
     {
     internal class Program
     {
         private static void Main(string[] args)
         {
             //Create a template service
             var service = new TemplateServiceXml();
    
             //Get the Razor template (most likely from a file or database)
             var razorTemplate =
                 "@using System <h1>Root</h1><p>Attribute 'testAttribute' = @Model.Attributes[\"testAttribute\"].InternalValue</p><p>Value of node = @Model.InternalValue</p>";
    
             //Get the XML to transform (most like passed to you from whoever is calling this)
             var xmlToTransform = "<Flat testAttribute=\"ValueOfTestAttribute\">ValueOfSingleRootFlatNode</Flat>";
    
             //Perform the transform
             var html = service.Parse(razorTemplate, xmlToTransform);
    
             //View the result
             Console.WriteLine(html);
    
             Console.ReadKey();
         }
     }
     }
    

Common Scenarios

It will be likely you want to get to nested XML elements, not just the root level like the example above. In order to do this, you need to cast the item in question to an "Object", then you can use the queryable extension methods "Where" and "Select" on it. An common example Razor view would start with the following "Using" statements and model delcaration:

        @using System
        @using System.Linq
        @using RazorEngineFromXml
        @model dynamic

When you want to use "Where" or "Select", cast "Elements" to an Object:

        @{
            object items = Model.Elements;
        }

You can get either an Attribute value, or the inner value of a node:

        @foreach (var currItem in items.Where(i => !string.IsNullOrEmpty(i.InternalValue)))
        {
            var nodeValue = currItem.InternalValue;
            var attributeValue = currItem.Attributes[\"testAttribute\"].InternalValue;
        }
⚠️ **GitHub.com Fallback** ⚠️