2010-09-15 67 views
0

看着教程顯示,但無法得到這個工作:生成一個XML的文件和XML格式

的Default.aspx:

<%@ Page Language="C#" ContentType="text/xml" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="rssPubba.Default" %> 

default.aspx.cs

protected void Page_Load(object sender, EventArgs e) 
    { 
     Response.ContentType = "text/xml"; 
     Response.ContentEncoding = Encoding.UTF8; 

     XmlDocument doc = new XmlDocument(); 

     // XML declaration 
     XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, null, null); 
     doc.AppendChild(declaration); 

     // Root element: article 
     XmlElement root = doc.CreateElement("article"); 
     doc.AppendChild(root); 

     // Sub-element: author 
     XmlElement author = doc.CreateElement("author"); 
     author.InnerText = "Faisal Khan"; 
     root.AppendChild(author); 

     // Attribute: isadmin 
     XmlAttribute isadmin = doc.CreateAttribute("isadmin"); 
     isadmin.Value = "true"; 
     author.Attributes.Append(isadmin); 

     // Sub-element: title 
     XmlElement title = doc.CreateElement("title"); 
     title.InnerText = "Sample XML Document"; 
     root.AppendChild(title); 

     // Sub-element: body (CDATA) 
     XmlElement body = doc.CreateElement("body"); 
     XmlNode cdata = doc.CreateCDataSection("This is the body of the article."); 
     body.AppendChild(cdata); 
     root.AppendChild(body); 

     doc.Save(Response.OutputStream); 
    } 

但是當我嘗試將其顯示在瀏覽器似乎將其解釋爲標記:

輸出:

<article> 
    <author isadmin="true">Faisal Khan</author> 
    <title>Sample XML Document</title> 
    <body><![CDATA[This is the body of the article.]]></body> 
</article> 

我必須做些什麼改變?

回答

0

我懷疑它會清除輸出到目前爲止,並寫入正常的頁面數據。兩個選項:

  • 使用ashx而不是aspx創建一個處理程序,以便它知道您不試圖渲染頁面。這可能是最明智的方法,如果它的總是意味着要生成一個XML文檔。
  • 寫完數據後請完成請求,例如通過調用Response.CompleteRequest()

(我也建議你使用LINQ to XML作爲構建XML文檔的比舊的DOM API相當更好的API,但它給你:)

+0

現在,我使用LINQ XML,Response.End();和一個ashx文件,它的工作原理!謝謝 – Mikael 2010-09-15 13:55:03

+0

是否可以使用Request「string city = Request.QueryString [」city「];」在ashx裏面? – Mikael 2010-09-15 14:12:17