Why does Response.Write("<someting>") not work in ASP.NET code-behind?
I have this code in my ASP.NET code-behind file:
Response.Write("<someting>")
开发者_如何转开发But it doesn't work. If I remove the <
tag delimiter, then it writes the content to the page.
My question is: how can I write an XML string to the page from a code-behind?
You need to HTML encode it:
Response.Write(HttpUtility.HtmlEncode("<someting>"));
But if you are writing an XML you should use a XDocument, XmlWriter or XmlDocument to build it first to ensure that it is valid and only then write it to the response.
What you're doing is already fine. Your <someting>
tag isn't showing on the page because the browser is expecting HTML, so it interprets <someting>
as an HTML tag it doesn't understand and displays nothing. If you look at the source of the page you should see the tag.
Your XMLHttpRequest (XHR) request should be able to read this data as XML without a problem, even though it's not displayed directly in the browser. However, as outlined in another answer, you should ideally change the content-type to text/xml
, so the client knows what data format to expect.
If you are outputting XML, you should first set the Content Type as follows:
Response.ContentType = "text/xml";
Also, it would probably be better to use a Handler (.ashx), not a page (.aspx), as it cuts out all sorts of extra page/form processing you don't need.
Then feel free to generate your page with Response.Write, eg:
Response.Write("<something>foobar</something>");
Since it's XML, you will need to view the generated output with an XML viewer. Internet Explorer will display well-formed XML as a tree-structure if you ensure the content type is correct.
You should also ensure XML content starts with:
<?xml version="1.0"?>
精彩评论