我试图找到一种简单的方法将参数从C#类文件(.cs)传递到.xslt文件。我不是真正使用.xml文件,所以我不知道像这样的http://msdn.microsoft.com/en-us/library/system.xml.xsl.xsltargumentlist.addparam.aspx是否对我有用。另外,我没有main方法,因为它只是一个类(全部在.net中完成)。有人知道这样做的可能方法吗?

        protected void Page_Load(object sender, EventArgs e)
    {
        XsltSettings settings = new XsltSettings();
        settings.EnableScript = true;
        FetchQuote();

        // Create the XslCompiledTransform and load the stylesheet
        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load("Home.xslt");

        // Create the XsltArgumentList
        XsltArgumentList xslArg = new XsltArgumentList();

        // Add parameters
        xslArg.AddParam("chart_url", "","Chart_Url");
        xslArg.AddParam("last", "", "Last");
        xslArg.AddParam("change", "", "Change");
        xslArg.AddParam("perc_change", "", "Perc_Change");

        // Transform the File
        using (XmlWriter w = XmlWriter.Create("output.xml"))
        {
            xslt.Transform("", xslArg, w);
        }



    }

最佳答案

xsl:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:kso="nothin">

<xsl:param name="yourParam" />


   public static string Transform(string xml, string xsl, XsltArgumentList argsList)
        {
            XDocument selectedXml = XDocument.Parse(xml);
            XslCompiledTransform xmlTransform = new XslCompiledTransform();

            StringBuilder htmlOutput = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(htmlOutput);

            xmlTransform.Load(new XmlTextReader(new StringReader(xsl)));
            xmlTransform.Transform(selectedXml.CreateReader(), argsList, writer);

            return htmlOutput.ToString();
        }

 protected void Page_Load(object sender, EventArgs e)
{

 XsltArgumentList xslArg = new XsltArgumentList();

    // Add parameters
    xslArg.AddParam("chart_url", "","Chart_Url");
    xslArg.AddParam("last", "", "Last");
    xslArg.AddParam("change", "", "Change");
    xslArg.AddParam("perc_change", "", "Perc_Change");



  string output=Transform(string.empty,"Home.xslt",xslArg );

  Response.Clear();
  Response.Write(output);

  //or:
  //string output=Transform("<xmlroot/>","Home.xslt",xslArg );
 }

10-02 05:46