如何在 ASP.NET 中返回 XML [英] How to return XML in ASP.NET

查看:37
本文介绍了如何在 ASP.NET 中返回 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题.我的使命是学习 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.

我有一个 Web 表单,它有一个 jqGrid 数据网格,我想通过它提供 XML 数据阿贾克斯.不过,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>

根据我之前使用其他脚本语言的经验,我只想打印出 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();
}

这篇关于如何在 ASP.NET 中返回 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆