写入 xml 时出错:“第 1 列第 3 行错误:文档末尾有额外内容”

Adh*_*ham 3 c# xml asp.net

这里是我用来响应 xml 数据的 c# 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class xmlData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        Response.ContentType = "text/xml"; 
        String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"+
                     "<note>"+
                         "<to>Tove</to>"+
                         "<from>Jani</from>"+
                         "<heading>Reminder</heading>"+
                         "<body>Don't forget me this weekend!</body>"+
                      "</note>";

        Response.Write(xml);

    }
}
Run Code Online (Sandbox Code Playgroud)

但我遇到了这个错误..为什么?

This page contains the following errors:

error on line 3 at column 1: Extra content at the end of the document
Below is a rendering of the page up to the first error.
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

您需要调用Response.End以阻止在您的 XML 之后呈现页面的其余部分 - 或者最好不要将其作为“页面”放在首位。毕竟,它并不是真正的页面——它只是一些 XML。听起来您真的想要一个“处理程序”(ASHX 文件和一个实现 的类IHttpHandler),它不会自动为您添加任何内容。