2012-12-15 36 views
0

我通过使用自定义的ActionResult返回从控制器操作XML:应用XSLT到XML在Asp.NET MVC

public class XmlActionResult : ActionResult 
{ 
    /// <summary> 
    /// This class is a custom ActionResult that outputs the content of an XML document to the response stream 
    /// </summary> 

    private readonly XDocument _document; 
    public Formatting Formatting { get; set; } 
    public string MimeType { get; set; } 

    public XmlActionResult(XDocument document) 
    { 
     _document = document; 
     MimeType = "text/xml"; 
     Formatting = Formatting.None; 

    } 

    public override void ExecuteResult(ControllerContext context) 
    { 
     context.HttpContext.Response.Clear(); 
     context.HttpContext.Response.ContentType = MimeType; 

     using(var writer = new XmlTextWriter(context.HttpContext.Response.OutputStream, null) 
      { 
       Formatting = Formatting 

      }) 

     _document.WriteTo(writer); 
    } 
} 

这个输出XML树浏览器。我有一个转换XML的XSL文件,我将如何将样式表应用于XML输出?

+3

请停止将“ASP.NET MVC”简称为“MVC”。一个是框架,而另一个是独立于语言的设计模式。这就像打电话给IE - “互联网” –

+0

这是一个公平的点,道歉! –

+0

您想在服务器上或客户端浏览器上应用XSLT转换的位置? –

回答

0

Use XslCompiledTransform to apply any XSLT 1.0 stylesheet或使用第三方XSLT 2.0处理器(如Saxon 9或XmlPrime)来应用任何XSLT 2.0样式表。

通过在其上调用扩展方法CreateNavigator,您可以传入您的XDocument作为Transform方法XslCompiledTransform的第一个参数。

XslCompiledTransform proc = new XslCompiledTransform(); 
proc.Load("sheet.xsl"); 
poc.Transform(_document.CreateNavigator(), null, context.HttpContext.Response.OutputStream); 

要使用扩展方法,您需要一个using System.Xml.XPath;指令。根据转换结果(例如,对于内容类型text/html还是对于内容类型application/xhtml + xml或其他某种格式的XHTML),您可能需要更改发送给浏览器的ContentType,以便转换结果被解析并适当渲染。