XML StringWriter为空

时间:2011-09-26 21:19:03

标签: c# xml asp.net-3.5 stringwriter

我在XMLDocument中有一些XML,我希望将其放入StringWriter,但它总是变为空(?)。我已经尝试用调试来检查变量,但是我仍然不知道发生了什么。

这就是我所拥有的:

        XmlDocument xmlInput = new XmlDocument();
        /* after this executes, xmlInput has lots of data in it */  
        xmlInput.LoadXml(...); 

        XslCompiledTransform transform = new XslCompiledTransform();
        /* I'm pretty sure Template.xslt is being found and loaded correctly */
        transform.Load(Server.MapPath("/Files/Template.xslt")); 

        using (System.IO.StringWriter sb = new System.IO.StringWriter())
        {
            XmlWriterSettings xSettings = new XmlWriterSettings();
            xSettings.ConformanceLevel = ConformanceLevel.Fragment;
            xSettings.Encoding = Encoding.UTF8;
            /* PROBLEM: After this line, StringWriter sb is {} */
            using (XmlWriter xWriter = XmlWriter.Create(sb, xSettings))
            {
                transform.Transform(xmlInput, xWriter);
            }

            /* xmlText is empty string "" after this line */
            String xmlText = sb.ToString();

            /* ... does more stuff ... */
        }

我可以帮忙吗?我真的不确定从哪里开始工作。

编辑:更多的调查:

        using (var stringWriter = new StringWriter())
        {
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
                /* Prints lots of data to the screen */
                Response.Write(xmlInput.InnerXml);

                xmlInput.WriteTo(xmlTextWriter);
                /* Doesn't print anything to the screen */
                Response.Write(stringWriter.GetStringBuilder().ToString() );
            }
        }

但是,冲洗就可以了。

                xmlInput.WriteTo(xmlTextWriter);
                xmlTextWriter.Flush();
                /* prints lots of data */
                Response.Write( stringWriter.GetStringBuilder().ToString() );

1 个答案:

答案 0 :(得分:0)

事实证明,我尝试应用的XSLT文件需要将XML包装在某个元素中。

flush()技巧帮了很多忙。