2012-10-23 91 views
0

如何設置一個場景,其中一個託管在X處的網站發佈的URL在瀏覽時將純粹返回XML。使用網站傳輸xml

其他地方的網頁會打這個URL,將XML加載到對象中。

所以我要像http://www.xml.com/document.aspx?id=1

的URL另一個網站將使用WebResponse類和WebRequest的對象,以得到從上面的頁面響應,我想回應是好的XML這樣我就可以使用XML來填充對象。

我確實做了一些工作,但響應包含呈現頁面所需的所有HTML,實際上我只是希望將XML作爲響應。

+0

可能重複:http://stackoverflow.com/questions/2295892/how-can-i-output-xml-from-code-behind-in-an-aspx-file – RemarkLima

回答

0

可能最好的辦法是使用HttpHandler/ASHX文件,但如果你想用頁面來完成它,這是完全可能的。兩個關鍵點是:

  1. 使用空白頁面。所有你想要在你的ASPX的標記是 <%Page ...%>指令。
  2. 設定的響應流 的contentType中以XML - Response.ContentType = "text/xml"

你如何生成XML本身是你的,但如果XML表示對象圖,你可以使用一個XmlSerializer(從System.Xml.Serialization命名空間)將XML直接寫入響應流,例如

using System.Xml.Serialization; 

// New up a serialiser, passing in the System.Type we want to serialize 
XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); 

// Set the ContentType 
Response.ContentType = "text/xml"; 

// Serialise the object to XML and pass it to the Response stream 
// to be returned to the client 
serialzer.Serialize(Response.Output, MyObject); 

如果您已經擁有了XML,那麼一旦你設置contentType中,你只需要把它寫入響應流,然後結束並刷新流。

// Set the ContentType 
Response.ContentType = "text/xml"; 

Response.Write(myXmlString); 

Response.Flush(); 
Response.End(); 
+0

嗯,我已經有XML我只想把它作爲一個字符串的另一端,沒有fanciness只是通過互聯網發送一個字符串,它會是XML。歡呼 –

+0

我很無聊,我不能看到我怎麼用這個來發送字符串 –

+0

@RobertHancliff更新了關於輸出一個簡單的XML字符串的信息 – PhilPursglove