generate a XML-File and display it in XML-format
Looked at a tutorial but couldn't get this working:
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);
}
however when I try to display it the browser seem to interpreting it as markup:
output:
<article>
<author isadmin="true">Faisal Khan</author>
<title>Sample XML Document</title>
<body><![CDATA[This is the body of the article.]]></body>
</article>
What changes to I have to 开发者_运维问答make?
I suspect it's clearing the output so far and writing the normal page data. Two options:
- Use an ashx instead of aspx to create a handler, so that it knows you're not trying to render the page. That's probably the most sensible approach, if it's always meant to be generating an XML document.
- Complete the request when you've written the data, e.g. by calling
Response.CompleteRequest()
(I'd also recommend using LINQ to XML as a rather nicer API for constructing XML documents than the old DOM API, but it's up to you :)
精彩评论