1

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?

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
LB.
  • 13,730
  • 24
  • 67
  • 102
  • You have something wierd going on there? I've just tried the code exactly as you have it and it works fine, even if I write something to Response before hand. – Martin Brown Apr 07 '09 at 16:01
  • I have no idea why this isn't working. I just tried it on a new project and it works well. Just not in my VPC environment. – LB. Apr 07 '09 at 16:19
  • This is very strange, it now works without any changes. – LB. Apr 07 '09 at 16:35

3 Answers3

2

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
  • 106,783
  • 21
  • 203
  • 265
2

Try using this:

XmlTextWriter xmlWriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument(false);
xmlWriter.WriteStartElement("userInfo");
HoLyVieR
  • 10,985
  • 5
  • 42
  • 67
Xerxis
  • 21
  • 1
1

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
  • 14,826
  • 2
  • 51
  • 81
  • still the same thing. I have this code in the Page_Load, would this affect it ? – LB. Apr 07 '09 at 15:55