如何在ASP.NET中返回XML如何在、ASP、XML、NET

2023-09-10 18:25:49 作者:情话再甜只是敷衍

这是一个非常基本的问题。我只是在我的任务是学习ASP.NET(C#)。我以前做过传统的ASP和PHP。

This is a very basic question. I'm just on my mission to learn ASP.NET (C#). I've done classic ASP and PHP before.

对于这个项目我有 ASP.NET 2.0 在我的手中。

For this project I have ASP.NET 2.0 at my hands.

我有,有一个 jqGrid的 Datagrid的,我要养活通过AJAX的XML数据的Web窗体。 jqGrid的不是这里的问题,虽然。 问题是,我应该好好地生成XML的办法。

I have a Web Form that has a jqGrid Datagrid that I want to feed XML data via AJAX. jqGrid is not the problem here, though. The "problem" is the approach that I should take to generate the XML.

我要如何做,在ASP.NET?

How do I do that in ASP.NET?

请我创建生成一个新的Web窗体的数据? 请我用一个新的Web服务(这将不会返回我需要的XML,不是吗?)? 请我莫名其妙地把一个函数,显示表中现有Web窗体?如果是这样,怎么?

在作出这一决定:我如何输出XML?我不希望使用ASP.NET中的任何XML组件,因为它只是简单的,简单的XML与后对方一个记录。使用的System.Xml将太多的开销在这里有道理的。

After that decision is made: How do I output the XML? I don't want to use any XML components of ASP.NET, because it's just plain, simplistic XML with one record after each other. Using System.Xml would be too much overhead to be justified here.

<?xml version='1.0' encoding='utf-8'?>
<rows>
<page>1</page>
<total>25</total>
<records>3</records>
  <row id='1'>
    <cell>Row 1, Column 1</cell>
    <cell>Row 1, Column 2</cell>
    <cell>Row 1, Column 3</cell>
  </row>
  <row id='2'>
    <cell>Row 2, Column 1</cell>
    <cell>Row 2, Column 2</cell>
    <cell>Row 2, Column 3</cell>
  </row>
  <row id='3'>
    <cell>Row 3, Column 1</cell>
    <cell>Row 3, Column 2</cell>
    <cell>Row 3, Column 3</cell>
  </row>
</rows>

这是我的$ P $与其他脚本语言pvious经验,我只是想打印出XML标记的数据流(的Response.Write)。我会去地狱,如果我在ASP.NET这样做?

From my previous experience with the other scripting languages, I'd just like to print out a stream of XML tags (Response.Write). Will I go to hell if I do so in ASP.NET?

推荐答案

另一种解决方案中的ashx使用一个完全成熟的XmlDocument / LINQ的是使用的XmlWriter,手之间各具特色的XML作为字符串排序的中途溶液和使用DOM。

Another solution to using a full blown XmlDocument/Linq in the ashx is to use the XmlWriter, sort of a halfway solution between hand crafting the xml as a string and using a dom.

是这样的:

StringBuilder query = new StringBuilder();

using (XmlWriter xmlWriter = XmlWriter.Create(query))
{
    xmlWriter.WriteStartElement("rows");
    xmlWriter.WriteElementString("page", "1");

    foreach(...)
    {

        xmlWriter.WriteStartElement("rows");
        xmlWriter.WriteAttributeString("row", "1");

        foreach(...)
        {
            xmlWriter.WriteElementString("cell", "Row 1, Column 1");
        }

        xmlWriter.WriteEndElement();            
    }

    xmlWriter.WriteEndElement();
}