How to write XML document using .NET?

Discussion in 'XML' started by anonieko@hotmail.com, Feb 28, 2005.

  1. Guest

    >
    >
    >
    >

    Writing an XML document the .Net way

    If you've been using the .Net Framework for even a week, you know that
    the kids in Redmond really thought of almost everything, so they're not
    going to make you concatenate huge strings to build an XML document.
    For our example, we're going to create a new page on our site called
    NewsWire.aspx and use that as the URL for our RSS feed. We're going to
    make the .aspx file contain only two lnes:

    <%@ Page Codebehind="NewsWire.aspx.cs"
    Inherits="UberAspNet.RSS.NewsWire" EnableViewState="false" %>
    <%@ OutputCache Duration="300" VaryByParam="none" %>
    The first line you've seen before. The second line tells ASP.NET to
    cache the entire page in memory and not run the code until 300 seconds
    have passed. You can put whatever value you want here, but if the data
    you're going to display changes infrequently, there's no harm really in
    cranking it up. Cached output is a lot faster than executing code and
    hitting a database. The rest of the .aspx file contains nothing. No
    HTML, XML or links to nudies.

    Frankly, the code-behind isn't that complicated either. Here are the
    goods:

    C#

    using System;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Text;
    using System.Web;
    using System.Xml;

    namespace UberAspNet.RSS
    {
    public class NewsWire : System.Web.UI.Page
    {
    private void Page_Load(object sender, System.EventArgs e)
    {
    Response.Clear();
    Response.ContentType = "text/xml";
    XmlTextWriter objX = new XmlTextWriter(Response.OutputStream,
    Encoding.UTF8);
    objX.WriteStartDocument();
    objX.WriteStartElement("rss");
    objX.WriteAttributeString("version","2.0");
    objX.WriteStartElement("channel");
    objX.WriteElementString("title", "uberASP.Net NewsWire");
    objX.WriteElementString("link","http://www.uberasp.net/newswire.aspx");
    objX.WriteElementString("description","The latest headlines and
    articles from the world of ASP.NET, Microsoft's
    Web development platform.");
    objX.WriteElementString("copyright","(c) 2004, POP World Media, LLC.
    All rights reserved.");
    objX.WriteElementString("ttl","5");
    SqlConnection objConnection = new
    SqlConnection(ConfigurationSettings.AppSettings["MyConnectionString"]);
    objConnection.Open();
    string sql = "SELECT TOP 10 Title, Summary, ArticleID, PostTime FROM
    Articles ORDER BY PostTime DESC";
    SqlCommand objCommand = new SqlCommand(sql, objConnection);
    SqlDataReader objReader = objCommand.ExecuteReader();
    while (objReader.Read())
    {
    objX.WriteStartElement("item");
    objX.WriteElementString("title",objReader.GetString(0));
    objX.WriteElementString("description",objReader.GetString(1));
    objX.WriteElementString("link","http://www.uberasp.net/GetArticle.aspx?id="
    + objReader.GetInt32(2).ToString());
    objX.WriteElementString("pubDate",
    objReader.GetDateTime(3).ToString("R"));
    objX.WriteEndElement();
    }
    objReader.Close();
    objConnection.Close();

    objX.WriteEndElement();
    objX.WriteEndElement();
    objX.WriteEndDocument();
    objX.Flush();
    objX.Close();
    Response.End();
    }
    }
    }
    VB .Net

    Imports System
    Imports System.Configuration
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Text
    Imports System.Web
    Imports System.Xml


    Namespace UberAspNet.RSS

    Public Class NewsWire
    Inherits System.Web.UI.Page

    Private Sub Page_Load(sender As Object, e As System.EventArgs)
    Response.Clear()
    Response.ContentType = "text/xml"
    Dim objX As New XmlTextWriter(Response.OutputStream,
    Encoding.UTF8)
    objX.WriteStartDocument()
    objX.WriteStartElement("rss")
    objX.WriteAttributeString("version", "2.0")
    objX.WriteStartElement("channel")
    objX.WriteElementString("title", "uberASP.Net NewsWire")
    objX.WriteElementString("link",
    "http://www.uberasp.net/newswire.aspx")
    objX.WriteElementString("description", "The latest headlines
    and articles from the world of ASP.NET,
    Microsoft's Web development platform.")
    objX.WriteElementString("copyright", "(c) 2004, POP World
    Media, LLC. All rights reserved.")
    objX.WriteElementString("ttl", "5")
    Dim objConnection As New
    SqlConnection(ConfigurationSettings.AppSettings("MyConnectionString"))
    objConnection.Open()
    Dim sql As String = "SELECT TOP 10 Title, Summary, ArticleID,
    PostTime FROM Articles ORDER BY PostTime DESC"
    Dim objCommand As New SqlCommand(sql, objConnection)
    Dim objReader As SqlDataReader = objCommand.ExecuteReader()
    While objReader.Read()
    objX.WriteStartElement("item")
    objX.WriteElementString("title", objReader.GetString(0))
    objX.WriteElementString("description",
    objReader.GetString(1))
    objX.WriteElementString("link",
    "http://www.uberasp.net/GetArticle.aspx?id=" +
    objReader.GetInt32(2).ToString())
    objX.WriteElementString("pubDate",
    objReader.GetDateTime(3).ToString("R"))
    objX.WriteEndElement()
    End While
    objReader.Close()
    objConnection.Close()

    objX.WriteEndElement()
    objX.WriteEndElement()
    objX.WriteEndDocument()
    objX.Flush()
    objX.Close()
    Response.End()
    End Sub
    End Class
    End Namespace
    First we show which namespaces we'll need. System.Text is necessary
    because we're accessing the Encoding class. Naturally since we're
    creating XML, we also need System.Xml.

    Once we get to the actual Page_Load processing, we clear the Response
    object and set its ContentType to "text/xml." Then we create an
    XmlTextWriter object that will do all of the heavy lifting. In our
    case, we're outputting it to Response.OutputStream, but you could just
    as easily output to a FileStream object and save it as a file.

    The rest of the code reads a lot like the output that it will create.
    We must start the document with the XmlTextWriter's
    WriteStartDocument() method and end with the WriteEndDocument() method.
    The first line that declares this as an XML document is created for us.
    If we're going to create an element that doesn't have any child nodes,
    we simply use the WriteElementString() method. If the element will have
    child nodes, we have to start it with the WriteStartElement() method
    and end it with the WriteEndElement().
    , Feb 28, 2005
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Tony Prichard
    Replies:
    0
    Views:
    714
    Tony Prichard
    Dec 12, 2003
  2. Manish Hatwalne
    Replies:
    1
    Views:
    391
    Martin Honnen
    Jul 13, 2004
  3. jullag
    Replies:
    20
    Views:
    290
    Frances
    Sep 22, 2005
  4. icogs
    Replies:
    0
    Views:
    125
    icogs
    Jan 31, 2008
  5. Frank Peterson
    Replies:
    9
    Views:
    218
    David Mark
    Jun 28, 2009
Loading...

Share This Page