2012-10-23 54 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