Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Dundas Dashboard
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » XML .NET » How to generate an XML document programmatically-using SAX technology: Part II

How to generate an XML document programmatically-using SAX technology: Part II

In the previous article, we’ve proceed to generate an XML document using DOM technology which is document object model, Now, we’ll do the same thing but, this time using SAX technology.

Author Rank:
Technologies: .NET Compact Framework, XML,Visual C# .NET
Total downloads :
Total page views :  5542
Rating :
 5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor


Related EbooksTop Videos

In the previous article, we've proceed to generate an xml document using DOM technology which is document object model, Now, we'll do the same thing but, this once, using SAX technology.  In fact the SAX or Serial Access parser for Xml is an API dedicated to whom want to manipulate xml files, it's provides mechanism of data reading from  and data writing in xml documents, but you tell me OK, so what is the difference? Or what's new? The DOM is also an API for manipulating XML documents. I tell you it's a legitimate question but this is out of the scope of this tutorial. Never the less; I can say that there is a difference in nature between the two concepts. And I can resume the difference in the following schedule.

DOM SAX
There are formal specifications for the DOM There aren't formal specifications within SAX
The entire xml tree must be in memory before the parser begins to parse It is no compulsory for the entire xml tree to be loaded before the parser begins to parse, it can work with the maximum depth of the given xml tree
Streamed reading from the disk is impossible Streamed reading from the disk is possible
Less problems during the XML validation More problems during the XML validation

If you want to dig into details concerning this issue, I advice you to read this article, browse to the following URL mentioned as follow   http://developerlife.com/tutorials/?p=28.

Now in order to use SAX, we need to define and instantiate an XmlTextWriter object. The last one can have three constructors overload techniques which ill enumerate them as below:

Constructor  Description
XmlTextWriter (TextWriter) Creates an instance of the XmlTextWriter class using the specified TextWriter.
XmlTextWriter (Stream, Encoding) Creates an instance of the XmlTextWriter class using the specified stream and encoding.
XmlTextWriter (String, Encoding)  Creates an instance of the XmlTextWriter class using the specified file and encoding.

In addition to those representations, I may add one XmlTextWriter (Console.Out) which enables  to display the xml content into  the console. So let's begin with this first one then try to enumerate the rest of techniques.

First way:

Create a new console application then copy and paste the code below:

static void Main(string[] args)

        {

            /*Instantiate an xml text writer and precise that the out put will be

            directed to the console*/

            XmlTextWriter writer = new XmlTextWriter(Console.Out);

            //This define if it is a stand alone xml file or not

            writer.WriteStartDocument(true);

            //This is a comment

            writer.WriteComment("This xml file representation is don with using SAX");

            //Start Familie element which is the parent element

            writer.WriteStartElement("Familie");

           

            //Father

            //Start by by create the element

            writer.WriteStartElement("Father");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My father");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(60);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Mother

            //Start by by create the element

            writer.WriteStartElement("Mother");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My mother");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(55);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Sister

            //Start by by create the element

            writer.WriteStartElement("Sister");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My sister");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(20);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Brother

            //Start by by create the element

            writer.WriteStartElement("Brother");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My borther");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(17);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Mark the end of the main element which is the familie element

            writer.WriteEndElement();

            //Mark the end of the document

            writer.WriteEndDocument();

            //Purge the memory

            writer.Flush();

            //Close the writer

            writer.Close();

            Console.Read();        

        }

Execute the code and observe. The following console will appear as below: 


 
Figure 1

Second way:

In this case an xml file will be generated in the defined emplacement. Replace the previous code with this one:

static void Main(string[] args)

        {

            /*Instantiate an xml text writer and precise the xml file path

            And the encoding type*/

      XmlTextWriter writer = new XmlTextWriter(@"C:\FamilyFile.xml", Encoding.ASCII);

            //This define if it is a stand alone xml file or not

            writer.WriteStartDocument(true);

            //This is a comment

            writer.WriteComment("This xml file representation is don with using SAX");

            //Start Familie element which is the parent element

            writer.WriteStartElement("Familie");

           

            //Father

            //Start by by create the element

            writer.WriteStartElement("Father");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My father");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(60);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Mother

            //Start by by create the element

            writer.WriteStartElement("Mother");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My mother");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(55);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Sister

            //Start by by create the element

            writer.WriteStartElement("Sister");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My sister");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(20);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

            //Brother

            //Start by by create the element

            writer.WriteStartElement("Brother");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My borther");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(17);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Mark the end of the main element which is the familie element

            writer.WriteEndElement();

            //Mark the end of the document

            writer.WriteEndDocument();

            //Purge the memory

            writer.Flush();

            //Close the writer

            writer.Close();

            Console.WriteLine("The xml document is generated successfully!!!")

            Console.Read();        

        }

Now execute the code then browse to C:\FamilyFile.xml open it and observe.

Third way:

It's similar to the previous way except that in this time we will use a stream  instead of the file path

static void Main(string[] args)

        {

            //File stream instantiation

            FileStream oStream = new FileStream(@"C:\FamilyFile1.xml", FileMode.Create, FileAccess.Write);

            /*Instantiate an xml text writer and prcise that the out put will be

            directed to the console*/

            XmlTextWriter writer = new XmlTextWriter(oStream, Encoding.ASCII);

            //This define if it is a stand alone xml file or not

            writer.WriteStartDocument(true);

            //This is a comment

            writer.WriteComment("This xml file representation is don with using SAX");

            //Start Familie element which is the parent element

            writer.WriteStartElement("Familie");

           

            //Father

            //Start by by create the element

            writer.WriteStartElement("Father");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My father");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(60);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Mother

            //Start by by create the element

            writer.WriteStartElement("Mother");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My mother");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(55);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Sister

            //Start by by create the element

            writer.WriteStartElement("Sister");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My sister");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(20);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

            //Brother

            //Start by by create the element

            writer.WriteStartElement("Brother");

            //Add the name attribute

            writer.WriteStartAttribute("Name");

            //Add the name value

            writer.WriteValue("My borther");

            //Mark the name attribute end

            writer.WriteEndAttribute();

            //Add the age attribute

            writer.WriteStartAttribute("Age");

            //Add the age value

            writer.WriteValue(17);

            //Mark the age attribute end

            writer.WriteEndAttribute();

            //Mark the end of the element

            writer.WriteEndElement();

 

            //Mark the end of the main element which is the familie element

            writer.WriteEndElement();

            //Mark the end of the document

            writer.WriteEndDocument();

            //Purge the memory

            writer.Flush();

            //Close the writer

            writer.Close();

            Console.WriteLine("The xml document is generated successfully!!!");

            Console.Read();        

        }

Now, browse to C:\FamilyFile1.xml then open it and observe.

Forth way:

static void Main(string[] args)

        {

            //Instanciate a string builder then add the xml content to it

            StringBuilder oStringBuilder = new StringBuilder();

            oStringBuilder.Append("<?xml version='1.0' encoding='us-ascii' standalone='yes'?>");

            oStringBuilder.Append("<!--This xml file representation is don with using SAX-->");

            oStringBuilder.Append("<Familie>");

            oStringBuilder.Append("<Father Name='My father' Age='60' />");

            oStringBuilder.Append("<Mother Name='My mother' Age='55' />");

            oStringBuilder.Append("<Sister Name='My sister' Age='20' />");

            oStringBuilder.Append("<Brother Name='My borther' Age='17' />");

            oStringBuilder.Append("</Familie>");

 

            //Add a new string writer and overload it by the above string builder instance

            TextWriter oTextStringWriter = new StringWriter(oStringBuilder);

            //Now overload the xmltext writer by the text writer instance

            XmlTextWriter writer = new XmlTextWriter(oTextStringWriter);

            Console.WriteLine("This xmltextwriter is ready to be used");

           

            Console.Read();        

        }

This is the forth and the last way to generate an xml entity using SAX technology.

Good dotneting!!!


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Bechir Bejaoui
The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT". He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved