我寫了一個ASHX通用處理程序來輸出XML。但是,由於某些原因,ASP.net會在打破XML的輸出結尾添加大量空白字符。爲什麼ASP.net在我的ASHX文件的輸出末尾寫入空格?
我的代碼如下所示:
context.Response.ContentType = 「文本/ XML」;
XmlSerializer oSerializer = new XmlSerializer(typeof(ModelXml[]),new XmlRootAttribute("rows"));
System.IO.MemoryStream ms2 = new System.IO.MemoryStream();
System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms2,new System.Text.UTF8Encoding());
oSerializer.Serialize(tw,models);
string s = System.Text.Encoding.UTF8.GetString(ms2.GetBuffer());
tw.Close();
ms2.Close();
context.Response.Write(s.Trim());
context.Response.End();
當我運行這段代碼直通調試器,我看到字符串s
確實包含的無空白的XML數據。然而,當我點Internet Explorer訪問這個文件,我得到以下錯誤:
The XML page cannot be displayed
Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.
--------------------------------------------------------------------------------
Invalid at the top level of the document. Error processing resource 'http://localhost:5791/XXXXX.ashx'.
當我查看記事本頁面的源代碼,我看到文件以正確的XML,但有附加很多空間到最後。如果我刪除這些空格,則XML文件可以正常使用我的瀏覽器和應用程序。
爲什麼ASP.net將這些空格添加到輸出中,我該怎麼辦?
你的XML看起來像什麼? – Kev 2011-06-14 16:54:33