在c#中使用xsl转换xml显示空文件

时间:2014-03-20 12:45:47

标签: c# asp.net xml xslt

我正在尝试使用xsl文件转换xml文件,并在新窗口中打开转换后的xml文件。我从sql server数据库中获取xml和xsl文件作为字符串,将它们转换为xml文档,然后使用xsl转换xml文件,下面是我的代码

IQueryable<DataDictionaryReport> reportsQuery = from d in dataDictionaryContext.DataDictionaryReports
                                                         where d.DBID == j
                                                         select d;
        string displayXML=null ;
        string displayXSL=null;

        foreach (var report in reportsQuery)
        {
            displayXML = report.ReportXML;
            displayXSL = report.ReportXSL;
        }

        //myLabel.Text = displayXML;

        XmlDocument docXML = new XmlDocument();
        docXML.LoadXml(displayXML);
        XmlTextWriter writerXML = new XmlTextWriter(Server.MapPath("/document/Model Report.xml"), null);
        writerXML.Formatting = Formatting.Indented;
        docXML.Save(writerXML);

        XmlDocument docXSL= new XmlDocument();
        docXSL.LoadXml(displayXSL);
        XmlTextWriter writerXSL = new XmlTextWriter(Server.MapPath("/document/Model Report.xsl"), null);
        writerXSL.Formatting = Formatting.Indented;
        docXSL.Save(writerXSL);

try
{
  XmlTextWriter writer = new XmlTextWriter(Server.MapPath("/document/output.xml"), null);
  XslCompiledTransform xslt = new XslCompiledTransform();
  xslt.Load("/document/Model Report.xsl");
  xslt.Transform("/document/Model Report.xml", "/document/output.xml"); 
 }
 catch (Exception ex)
 {
   Console.WriteLine(ex.ToString());
  }

 string newWin = "window.open('" + "/document/output.xml" + "');";
 ClientScript.RegisterStartupScript(this.GetType(), "pop", newWin, true);

我的output.xml显示一个空文件。我发布了xsl文件的前几行代码,可能太长了,

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:key name="IDs" match="*" use="@id" />
    <xsl:template match="/">
        <html xmlns="http://www.w3.org/1999/xhtml">
           <head>
              <title>Table/Columns Report</title>
              <script type="text/javascript">
               // <![CDATA[
               function toggle(element, togimg) {
                  if (element.style.display == 'none') {
                      element.style.display = 'block';
                      togimg.src="images/collapse.gif";
                  }
                  else {
                      element.style.display = 'none';
                      togimg.src="images/expand.gif";
                  }
               }
               // ]]></script>
            </head>
            ...

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

它显示一个空文件,错误通过将XML文档流式传输到内存然后从内存中读取来解决。代码如下,

MemoryStream stm = new MemoryStream();
xslt.Transform(docXML, null, stm);

stm.Position = 1;
StreamReader sr = new StreamReader(stm);
Response.Write(sr.ReadToEnd());