views:

572

answers:

2

I'm trying to generate XML and I encounter this exception:

XmlTextWriter xmlWriter = 
   new XmlTextWriter(Response.OutputStream, Encoding.UTF8);

xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("userInfo");

It gives me an exception:

WriteStartDocument needs to be the first call.

But as you can see, I did call the WriteStartDocument() first!

Any ideas?

+2  A: 

However there are already other things in the Response stream (e.g. HTTP headers).

Probably better to write XML to a StringWriter and then write the string to Response.

Richard
A: 

Don't forget to clear your aspx file of content so that only the Page directive is left, i.e.:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

Also use Response.Output instead of Response.OutputStream:

XmlTextWriter xmlWriter = new XmlTextWriter(Response.Output); 
xmlWriter.WriteStartDocument(); 
xmlWriter.WriteStartElement("userInfo");
xmlWriter.WriteEndElement();
Jakob Christensen
still the same thing. I have this code in the Page_Load, would this affect it ?
LB
It works for me in Page_Load.
Jakob Christensen