WriteStartDocument() 抛出 InvalidOperationException

发布于 2024-07-16 18:20:32 字数 342 浏览 0 评论 0原文

我正在尝试生成 XML,但遇到了此异常:

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

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

它给了我一个异常:

WriteStartDocument 需要是第一个调用。

但如您所见,我确实首先调用了 WriteStartDocument()!

有任何想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

邮友 2024-07-23 18:20:32

然而,响应流中已经存在其他内容(例如 HTTP 标头)。

最好将 XML 写入 StringWriter,然后将字符串写入 Response。

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.

初见你 2024-07-23 18:20:32

尝试使用这个:

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

Try using this:

XmlTextWriter xmlWriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument(false);
xmlWriter.WriteStartElement("userInfo");
会发光的星星闪亮亮i 2024-07-23 18:20:32

不要忘记清除 aspx 文件的内容,以便只留下 Page 指令,即:

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

还使用 Response.Output 而不是 Response.OutputStream:

XmlTextWriter xmlWriter = new XmlTextWriter(Response.Output); 
xmlWriter.WriteStartDocument(); 
xmlWriter.WriteStartElement("userInfo");
xmlWriter.WriteEndElement();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文