How to write XML document using .NET?

A

anonieko

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().
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,732
Latest member
ArronPalin

Latest Threads

Top