SamJolly
SamJolly

Reputation: 6477

Razor instead of XSLT to transform an XML Document in a MVC3/MVC4 application?

Background

I need to transform an XML Document to an XHTML document for conversion to a DOCX in a MVC3 web application. I will be merging in paragraph text around the XML data. The Paragraph text is extracted from a DB. In the past I would have certainly use XSLT to transform the XML. However I now realise that Razor provides a very compelling/better alternative. My XSLT is a little rusty now, and I will be using Razor heavily in my MVC application anyway. So is Razor the way to go?

If razor is the way to go then I would grateful as to how one would include this in say the controller. My initial pseudocode thoughts are along the line of:

  ViewBag.MyXMLDoc = DocXML;    
  var MyDocXHtml = View("XHtmlRazorRenderer", ParagraphTextListModel);

Thoughts greatly appreciated.

Edit

MyDocument = MyDocument.LoadXML("MyDocXML.xml")    
ViewBag.MyDocument = MyDocument;
var MyDocXHtml = View("XHtmlRazorRenderer", ParagraphTextListModel);

Upvotes: 3

Views: 1641

Answers (2)

Romias
Romias

Reputation: 14133

Maybe you can create a ViewModel that mimic the structure of your XML.

That way... you don't rely on ViewBag... and can loop throught the viewmodel properties and collections to generate the HTML using Razor.

The creation of the viewmodel should be made on the controller, loading the XML and then using xpath load the viewmodel.

Then, in Razor, using the ViewModel you generate the HTML.

Hope your XML is not too complex.

Your ViewModel:

public class MyViewModel{
   public ParsedXMLDoc myXmlData {get; set;}
   public ParagraphTextListModel paragraph {get; set;}
}

In your Controller just pass the MyViewModel to the view as the Model.

Upvotes: 0

Lucero
Lucero

Reputation: 60246

I'd stick with XSLT for the given job.

Note that Razor is a "generic" text templating engine, and it will do nothing to ease the generation of correct XML. Also, the traversal of complex XML with namespaces is IMHO much more natural and concise with XPath compared to LINQ-to-XML.

It's not too hard to generate a custom view engine that does the job of performing XSLT just like a Razor template renders text and HTML. This allows for a nice and natural integration of the XSLT rendering in the scope of the ASP.NET MVC application.

Upvotes: 2

Related Questions