Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I just built a site that transforms XML into HTML for display in MVC3. I used the second technique, where the controller determines the XML and XSLT files to use, and passes them in the model. An HTML helper in the view actually performs the transform.</p> <p>In this case I'm rendering a conference program, so that's what <code>Program</code> refers to below. Parameters can be supplied to the stylesheet; below, I'm supplying a base URL as a parameter that will be turned into links in the generated HTML.</p> <p>The model:</p> <pre><code>public class ProgramModel { public string ProgramFilename { get; set; } public string StylesheetFilename { get; set; } public Dictionary&lt;string, string&gt; Parameters { get; protected set; } public ProgramModel() { Parameters = new Dictionary&lt;string, string&gt;(); } } </code></pre> <p>The controller:</p> <pre><code> [OutputCache(Duration=1000)] public ActionResult Index() { string xmlFile = Server.MapPath("~/Program.xml"); string xsltFile = Server.MapPath("~/Program-index.xslt"); Response.AddCacheDependency(new CacheDependency(xmlFile), new CacheDependency(xsltFile)); ProgramModel model = new ProgramModel(); model.ProgramFilename = xmlFile; model.StylesheetFilename = xsltFile; model.Parameters["baseDayUrl"] = Url.Action("Day"); return View(model); } </code></pre> <p>The helper:</p> <pre><code>public static class HtmlHelperXmlExtensions { /// &lt;summary&gt; /// Applies an XSL transformation to an XML document. /// &lt;/summary&gt; public static HtmlString RenderXml(this HtmlHelper helper, string xmlPath, string xsltPath, IDictionary&lt;string,string&gt; parameters) { XsltArgumentList args = new XsltArgumentList(); if (parameters != null) foreach (string key in parameters.Keys) args.AddParam(key, "", parameters[key]); XslCompiledTransform t = new XslCompiledTransform(); t.Load(xsltPath); XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; settings.ValidationType = ValidationType.DTD; using (XmlReader reader = XmlReader.Create(xmlPath, settings)) { StringWriter writer = new StringWriter(); t.Transform(reader, args, writer); return new HtmlString(writer.ToString()); } } } </code></pre> <p>The view:</p> <pre><code>&lt;div data-role="content"&gt; @Html.RenderXml(Model.ProgramFilename, Model.StylesheetFilename, Model.Parameters) &lt;/div&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload