Ho appena creato un sito che trasforma XML in HTML per la visualizzazione in MVC3. Ho usato la seconda tecnica, in cui il controller determina i file XML e XSLT da utilizzare e li passa nel modello. Un helper HTML nella vista esegue effettivamente la trasformazione.
In questo caso sto eseguendo il rendering di un programma per conferenze, quindi questo è il riferimento a Program
. I parametri possono essere forniti al foglio di stile; di seguito, fornisco un URL di base come parametro che verrà trasformato in link nell'HTML generato.
Il modello:
public class ProgramModel
{
public string ProgramFilename { get; set; }
public string StylesheetFilename { get; set; }
public Dictionary<string, string> Parameters { get; protected set; }
public ProgramModel()
{
Parameters = new Dictionary<string, string>();
}
}
Il controllore:
[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);
}
L'helper:
public static class HtmlHelperXmlExtensions
{
/// <summary>
/// Applies an XSL transformation to an XML document.
/// </summary>
public static HtmlString RenderXml(this HtmlHelper helper, string xmlPath, string xsltPath, IDictionary<string,string> 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());
}
}
}
La vista:
<div data-role="content">
@Html.RenderXml(Model.ProgramFilename, Model.StylesheetFilename, Model.Parameters)
</div>
fonte
2011-10-06 22:14:58
Hai trovato una soluzione per questo? Cosa hai fatto? – XtremeBytes