473,394 Members | 2,100 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How to write XML document using .NET?

>


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.GetStrin g(0));
objX.WriteElementString("description",objReader.Ge tString(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("M yConnectionString"))
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().

Jul 20 '05 #1
0 1801

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: techy techno | last post by:
Hii Just wanted to know how can I decorate my texboxes and Listmenu which is called from a JS file using the following code below: document.write("<SELECT NAME='cur2' ONCHANGE='cconv1();'>");...
2
by: Geoff Wilkins | last post by:
I am using <SCRIPT src=...> to import a Javascript routine from a remote source. I am then using some of the variables given values in the routine, in my own Javascript.. Unfortunately the...
8
by: Ben | last post by:
Hi all, Just wondering how to write (using document.write) to a table cell. I have table with 3 rows and 3 colums. I want to write from within the Javascript to say third column of a first row....
13
by: Stumped and Confused | last post by:
Hello, I really, really, need some help here - I've spent hours trying to find a solution. In a nutshell, I'm trying to have a user input a value in form's textfield. The value should then be...
6
by: ok | last post by:
<img src="http://www.6park.com/enter2/av.gif" onload="document.write('an iframe obj');"> First of all, it destroy the HTML page. Secondly even if it does not destroy it, the iframe object will...
14
by: Eli | last post by:
I've got a script that I'm trying to debug which uses document.write() to place HTML within a page. In both IE6 and Firefox when I view source, I see only the script itself and not any HTML as...
4
by: Prowler | last post by:
In the application we are currently building, we need to write positioning code on-the-fly, based upon the screen offset of the element in the AS/400 application which drives the Web app. The 400,...
2
by: bissatch | last post by:
Hi, I am trying to use JavaScript to write a table column on a web page. The code is as follows: <html> <head> <script> function displaycount() {
25
by: jullag | last post by:
Hi, does anyone know of any javascript method that does the same job as document.write(), but not necessarily at the end of the document? For instance, insert some text inside an element that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.