LB.
LB.

Reputation: 14112

WriteStartDocument() throws InvalidOperationException

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?

Upvotes: 1

Views: 2412

Answers (3)

Xerxis
Xerxis

Reputation: 21

Try using this:

XmlTextWriter xmlWriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument(false);
xmlWriter.WriteStartElement("userInfo");

Upvotes: 2

Jakob Christensen
Jakob Christensen

Reputation: 14956

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();

Upvotes: 1

Richard
Richard

Reputation: 109005

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.

Upvotes: 2

Related Questions