Wednesday, August 27, 2008

Reading and Writing XML in C#

In this article, you will see how to read and write XML documents in Microsoft .NET using C# language. First, I will discuss XML .NET Framework Library namespace and classes. Then, you will see how to read and write XML documents. In the end of this article, I will show you how to take advantage of ADO.NET and XML .NET model to read and write XML documents from relational databases and vice versa.

Introduction to Microsoft .NET XML Namespaces and Classes

Before start working with XML document in .NET Framework, It is important to know about .NET namespace and classes provided by .NET Runtime Library. .NET provides five namespace - System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, and System.Xml.Xsl to support XML classes.

The System.Xml namespace contains major XML classes. This namespace contains many classes to read and write XML documents. In this article, we are going to concentrate on reader and write class. These reader and writer classes are used to read and write XMl documents. These classes are - XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter. As you can see there are four reader and two writer classes.

The XmlReader class is an abstract bases classes and contains methods and properties to read a document. The Read method reads a node in the stream. Besides reading functionality, this class also contains methods to navigate through a document nodes. Some of these methods are MoveToAttribute, MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement and MoveToNextAttribute. ReadString, ReadInnerXml, ReadOuterXml, and ReadStartElement are more read methods. This class also has a method Skip to skip current node and move to next one. We'll see these methods in our sample example.

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. As their name explains, they are used to read text, node, and schemas.

The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items. This class is base class for XmlTextWriter class, which we'll be using in our sample example.

The XmlNode class plays an important role. Although, this class represents a single node of XML but that could be the root node of an XML document and could represent the entire file. This class is an abstract base class for many useful classes for inserting, removing, and replacing nodes, navigating through the document. It also contains properties to get a parent or child, name, last child, node type and more. Three major classes derived from XmlNode are XmlDocument, XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an XML document and provides methods and properties to load and save a document. It also provides functionality to add XML items such as attributes, comments, spaces, elements, and new nodes. The Load and LoadXml methods can be used to load XML documents and Save method to save a document respectively. XmlDocumentFragment class represents a document fragment, which can be used to add to a document. The XmlDataDocument class provides methods and properties to work with ADO.NET data set objects.

In spite of above discussed classes, System.Xml namespace contains more classes. Few of them are XmlConvert, XmlLinkedNode, and XmlNodeList.

Next namespace in Xml series is System.Xml.Schema. It classes to work with XML schemas such XmlSchema, XmlSchemaAll, XmlSchemaXPath, XmlSchemaType.

The System.Xml.Serialization namespace contains classes that are used to serialize objects into XML format documents or streams.

The System.Xml.XPath Namespce contains XPath related classes to use XPath specifications. This namespace has following classes -XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. With the help of XpathDocument, XpathNavigator provides a fast navigation though XML documents. This class contains many Move methods to move through a document.

The System.Xml.Xsl namespace contains classes to work with XSL/T transformations.

Reading XML Documents

In my sample application, I'm using books.xml to read and display its data through XmlTextReader. This file comes with VS.NET samples. You can search this on your machine and change the path of the file in the following line:

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

Or you can use any XML file.

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. Besides XmlReader methods and properties, these classes also contain members to read text, node, and schemas respectively. I am using XmlTextReader class to read an XML file. You read a file by passing file name as a parameter in constructor.

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

After creating an instance of XmlTextReader, you call Read method to start reading the document. After read method is called, you can read all information and data stored in a document. XmlReader class has properties such as Name, BaseURI, Depth, LineNumber an so on.

List 1 reads a document and displays a node information using these properties.

About Sample Example 1

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of file and display the contents to the console output.

Sample Example 1.



using System;

using System.Xml;

namespace ReadXml1

{

class Class1

{

static void Main(string[] args)

{

// Create an isntance of XmlTextReader and call Read method to read the file

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

textReader.Read();

// If the node has value

while (textReader.Read())

{

// Move to fist element

textReader.MoveToElement();

Console.WriteLine("XmlTextReader Properties Test");

Console.WriteLine("===================");

// Read this element's properties and display them on console

Console.WriteLine("Name:" + textReader.Name);

Console.WriteLine("Base URI:" + textReader.BaseURI);

Console.WriteLine("Local Name:" + textReader.LocalName);

Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());

Console.WriteLine("Depth:" + textReader.Depth.ToString());

Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());

Console.WriteLine("Node Type:" + textReader.NodeType.ToString());

Console.WriteLine("Attribute Count:" + textReader.Value.ToString());

}

}

}

}




The NodeType property of XmlTextReader is important when you want to know the content type of a document. The XmlNodeType enumeration has a member for each type of XML item such as Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, WhiteSpace and so on.

List 2 code sample reads an XML document, finds a node type and writes information at the end with how many node types a document has.

About Sample Example 2

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of the file. After reading a node, I check its NodeType property to find the node and write node contents to the console and keep track of number of particular type of nodes. In the end, I display total number of different types of nodes in the document.

Sample Example 2.



using System;

using System.Xml;

namespace ReadingXML2

{

class Class1

{

static void Main(string[] args)

{

int ws = 0;

int pi = 0;

int dc = 0;

int cc = 0;

int ac = 0;

int et = 0;

int el = 0;

int xd = 0;

// Read a document

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

// Read until end of file

while (textReader.Read())

{

XmlNodeType nType = textReader.NodeType;

// If node type us a declaration

if (nType == XmlNodeType.XmlDeclaration)

{

Console.WriteLine("Declaration:" + textReader.Name.ToString());

xd = xd + 1;

}

// if node type is a comment

if (nType == XmlNodeType.Comment)

{

Console.WriteLine("Comment:" + textReader.Name.ToString());

cc = cc + 1;

}

// if node type us an attribute

if (nType == XmlNodeType.Attribute)

{

Console.WriteLine("Attribute:" + textReader.Name.ToString());

ac = ac + 1;

}

// if node type is an element

if (nType == XmlNodeType.Element)

{

Console.WriteLine("Element:" + textReader.Name.ToString());

el = el + 1;

}

// if node type is an entity\

if (nType == XmlNodeType.Entity)

{

Console.WriteLine("Entity:" + textReader.Name.ToString());

et = et + 1;

}

// if node type is a Process Instruction

if (nType == XmlNodeType.Entity)

{

Console.WriteLine("Entity:" + textReader.Name.ToString());

pi = pi + 1;

}

// if node type a document

if (nType == XmlNodeType.DocumentType)

{

Console.WriteLine("Document:" + textReader.Name.ToString());

dc = dc + 1;

}

// if node type is white space

if (nType == XmlNodeType.Whitespace)

{

Console.WriteLine("WhiteSpace:" + textReader.Name.ToString());

ws = ws + 1;

}

}

// Write the summary

Console.WriteLine("Total Comments:" + cc.ToString());

Console.WriteLine("Total Attributes:" + ac.ToString());

Console.WriteLine("Total Elements:" + el.ToString());

Console.WriteLine("Total Entity:" + et.ToString());

Console.WriteLine("Total Process Instructions:" + pi.ToString());

Console.WriteLine("Total Declaration:" + xd.ToString());

Console.WriteLine("Total DocumentType:" + dc.ToString());

Console.WriteLine("Total WhiteSpaces:" + ws.ToString());

}

}

}

Writing XML Documents

XmlWriter class contains the functionality to write to XML documents. It is an abstract base class used through XmlTextWriter and XmlNodeWriter classes. It contains methods and properties to write to XML documents. This class has several Writexxx method to write every type of item of an XML document. For example, WriteNode, WriteString, WriteAttributes, WriteStartElement, and WriteEndElement are some of them. Some of these methods are used in a start and end pair. For example, to write an element, you need to call WriteStartElement then write a string followed by WriteEndElement.

Besides many methods, this class has three properties. WriteState, XmlLang, and XmlSpace. The WriteState gets and sets the state of the XmlWriter class.

Although, it's not possible to describe all the Writexxx methods here, let's see some of them.

First thing we need to do is create an instance of XmlTextWriter using its constructor. XmlTextWriter has three overloaded constructors, which can take a string, stream, or a TextWriter as an argument. We'll pass a string (file name) as an argument, which we're going to create in C:\ root.

In my sample example, I create a file myXmlFile.xml in C:\\ root directory.

// Create a new file in C:\\ dir
XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null) ;

After creating an instance, first thing you call us WriterStartDocument. When you're done writing, you call WriteEndDocument and TextWriter's Close method.


textWriter.WriteStartDocument();
textWriter.WriteEndDocument();
textWriter.Close();

The WriteStartDocument and WriteEndDocument methods open and close a document for writing. You must have to open a document before start writing to it. WriteComment method writes comment to a document. It takes only one string type of argument. WriteString method writes a string to a document. With the help of WriteString, WriteStartElement and WriteEndElement methods pair can be used to write an element to a document. The WriteStartAttribute and WriteEndAttribute pair writes an attribute.

WriteNode is more write method, which writes an XmlReader to a document as a node of the document. For example, you can use WriteProcessingInstruction and WriteDocType methods to write a ProcessingInstruction and DocType items of a document.

//Write the ProcessingInstruction node
string PI= "type='text/xsl' href='book.xsl'"
textWriter.WriteProcessingInstruction("xml-stylesheet", PI);
//'Write the DocumentType node
textWriter.WriteDocType("book", Nothing, Nothing, "");

The below sample example summarizes all these methods and creates a new xml document with some items in it such as elements, attributes, strings, comments and so on. See Listing 5-14. In this sample example, we create a new xml file c:\xmlWriterText.xml. In this sample example, We create a new xml file c:\xmlWriterTest.xml using XmlTextWriter:

After that, we add comments and elements to the document using Writexxx methods. After that we read our books.xml xml file using XmlTextReader and add its elements to xmlWriterTest.xml using XmlTextWriter.

About Sample Example 3

In this sample example, I create a new file myxmlFile.xml using XmlTextWriter and use its various write methods to write XML items.

Sample Example 3.

using System;

using System.Xml;

namespace ReadingXML2

{

class Class1

{

static void Main(string[] args)

{

// Create a new file in C:\\ dir

XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);

// Opens the document

textWriter.WriteStartDocument();

// Write comments

textWriter.WriteComment("First Comment XmlTextWriter Sample Example");

textWriter.WriteComment("myXmlFile.xml in root dir");

// Write first element

textWriter.WriteStartElement("Student");

textWriter.WriteStartElement("r", "RECORD", "urn:record");

// Write next element

textWriter.WriteStartElement("Name", "");

textWriter.WriteString("Student");

textWriter.WriteEndElement();

// Write one more element

textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony");

textWriter.WriteEndElement();

// WriteChars

char[] ch = new char[3];

ch[0] = 'a';

ch[1] = 'r';

ch[2] = 'c';

textWriter.WriteStartElement("Char");

textWriter.WriteChars(ch, 0, ch.Length);

textWriter.WriteEndElement();

// Ends the document.

textWriter.WriteEndDocument();

// close writer

textWriter.Close();

}

}

}




Using XmlDocument

The XmlDocument class represents an XML document. This class provides similar methods and properties we've discussed earlier in this article.

Load and LoadXml are two useful methods of this class. A Load method loads XML data from a string, stream, TextReader or XmlReader. LoadXml method loads XML document from a specified string. Another useful method of this class is Save. Using Save method you can write XML data to a string, stream, TextWriter or XmlWriter.

About Sample Example 4

This tiny sample example pretty easy to understand. We call LoadXml method of XmlDocument to load an XML fragment and call Save to save the fragment as an XML file.

Sample Example 4.

//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml(("Tommy
ex
"));
//Save the document to a file.
doc.Save("C:\\std.xml");
You can also use Save method to display contents on console if you pass Console.Out as a
arameter. For example:
doc.Save(Console.Out);

About Sample Example 5

Here is one example of how to load an XML document using XmlTextReader. In this sample example, we read books.xml file using XmlTextReader and call its Read method. After that we call XmlDocumetn's Load method to load XmlTextReader contents to XmlDocument and call Save method to save the document. Passing Console.Out as a Save method argument displays data on the console

Sample Example 5.

XmlDocument doc = new XmlDocument();
//Load the the document with the last book node.
XmlTextReader reader = new XmlTextReader("c:\\books.xml");
reader.Read();
// load reader
doc.Load(reader);
// Display contents on the console
doc.Save(Console.Out);

Writing Data from a database to an XML Document

Using XML and ADO.NET mode, reading a database and writing to an XML document and vice versa is not a big deal. In this section of this article, you will see how to read a database table's data and write the contents to an XML document.

The DataSet class provides method to read a relational database table and write this table to an XML file. You use WriteXml method to write a dataset data to an XML file.

In this sample example, I have used commonly used Northwind database comes with Office 2000 and later versions. You can use any database you want. Only thing you need to do is just chapter the connection string and SELECT SQ L query.

About Sample Example 6

In this sample, I reate a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter.

In this sample example, I have used OldDb data provides. You need to add reference to the Syste.Data.OldDb namespace to use OldDb data adapters in your program. As you can see from Sample Example 6, first I create a connection with northwind database using OldDbConnection. After that I create a data adapter object by passing a SELECT SQL query and connection. Once you have a data adapter, you can fill a dataset object using Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and write its contents to the XML document. In our sample, we read Customers table records and write DataSet contents to OutputXml.Xml file in C:\ dir.

Sample Example 6.

using System;

using System.Xml;

using System.Data;

using System.Data.OleDb;

namespace ReadingXML2

{

class Class1

{

static void Main(string[] args)

{

// create a connection

OleDbConnection con = new OleDbConnection();

con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";

// create a data adapter

OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con);

// create a new dataset

DataSet ds = new DataSet();

// fill dataset

da.Fill(ds, "Customers");

// write dataset contents to an xml file by calling WriteXml method

ds.WriteXml("C:\\OutputXML.xml");

}

}

}


Summary

.NET Framework Library provides a good support to work with XML documents. The XmlReader, XmlWriter and their derived classes contains methods and properties to read and write XML documents. With the help of the XmlDocument and XmlDataDocument classes, you can read entire document. The Load and Save method of XmlDocument loads a reader or a file and saves document respectively. ADO.NET provides functionality to read a database and write its contents to the XML document using data providers and a DataSet object.

Monday, August 25, 2008

Legal and Logical Explained

After having failed his exam in "Logistics and Organization", a student goes and confronts his lecturer about it.

Student: "Sir, do you really understand anything about the subject?"

Professor: "Surely I must. Otherwise I would not be a professor!"

Student: "Great, well then I would like to ask you a question.

If you can give me the correct answer, I will accept my mark as is and go. If you however do not know the answer, I want you give me an "A" for the exam. "

Professor: "Okay, it's a deal. So what is the question?"

Student: "What is legal, but not logical, logical, but not legal, and neither logical, nor legal?"

Even after some long and hard consideration, the professor cannot give the student an answer, and therefore changes his exam mark into an "A", as agreed.

Afterwards, the professor calls on his best student and asks him the same question.

He immediately answers: "Sir, you are 63 years old and married to a 35 year old woman, which is legal, but not logical. Your wife has a 25 year old lover, which is logical, but not legal. The fact that you have given your wife's lover an "A", although he really should have failed, is neither legal, nor logical."

A very beautiful poem on today's fast life

' WAQT NAHI '

Har khushi Hai Logon Ke Daman Mein,
Par Ek Hansi Ke Liye Waqt Nahi.
Din Raat Daudti Duniya Mein,
Zindagi Ke Liye Hi Waqt Nahi.

Maa Ki Loree Ka Ehsaas To Hai,
Par Maa Ko Maa Kehne Ka Waqt Nahi.
Saare Rishton Ko To Hum Maar Chuke,
Ab Unhe Dafnane Ka Bhi Waqt Nahi.

Saare Naam Mobile Mein Hain,
Par Dosti Ke Lye Waqt Nahi.
Gairon Ki Kya Baat Karen,
Jab Apno Ke Liye Hi Waqt Nahi.

Aankhon Me Hai Neend Badee,
Par Sone Ka Waqt Nahi.
Dil Hai Ghamon Se Bhara Hua,
Par Rone Ka Bhi Waqt Nahi.

Paison ki Daud Me Aise Daude,
Ki Thakne ka Bhi Waqt Nahi.
Paraye Ehsason Ki Kya Kadr Karein,
Jab Apane Sapno Ke Liye Hi Waqt Nahi.

Tu Hi Bata E Zindagi,
Iss Zindagi Ka Kya Hoga,
Ki Har Pal Marne Walon Ko,
Jeene Ke Liye Bhi Waqt Nahi.......

Excerpts from AOL Sermons

What Enhances Your Beauty?



When your mind is not complaining, responsible, courageous, confident and hollow and empty you are inexplicably beautiful. A person who cannot correct or act has no right to complain. And when a person can correct or act, he will never complain. Complaining is a sign of weakness. Complaining is the nature of utter ignorance where one does not know the Self. Complaint takes away the Beauty that is inborn in you. And it shows up more on the one who is on this path.

Worldly mind is a complaining mind; Divine mind is a dancing mind. Just complaining without indicating the solution is irresponsibility. When the solutions are not workable, finding alternative solutions is Courage.
For external beauty, you put on things; for real Beauty, you have to drop all the things. For external beauty you have to have Make-up; for your real Beauty you only have to realize that you are MADE-UP!






The World Belongs to You


Pleasure or pain is an intense sensation in the four to six and half foot body. When we are not caught up in this then we are truly and sincerely able to say, "I belong to you." That is when all the cravings and aversions, desires and doubts fall off—and in a moment the world belongs to you. All your miseries surround the "I, I, I, . . . ", "I want this, I like that, I don't like this . . ." Just let go. The sun rises and sets, the grass grows, the river flows, the moon shines and I am here forever!

How do you feel if someone praises you?
Answer: "Shy, happy, great, embarrassed . . . "

It does something to you, doesn't it? It doesn't do anything to me! When you praise the moon, the mountains, Lake Lucerne, the Black Forest . . .it doesn't do anything to them. They remain the same.
Just like that I am part of nature. If you enjoy praising me, you may do so. In fact, you have no choice! (Laughter)

You can do with me whatever you like. I am there for you. I am your toy! (Laughter)






Dedication and Commitment


Just like you run out of fuel in the car and you have to refill it again and again, in the same way your dedication and commitment runs out in the course of time and it needs constant renewal!
You have to dedicate and rededicate again and again.

Often people take their dedication for granted and then the mind starts demanding or complaining. When dedication is not complete, it leads to grumbling and complaints.

Total dedication brings enormous enthusiasm, zeal, trust, and challenge, and does not leave any room for ego.






The Way Out of Sorrow


If your are unhappy you better check if one or all of these are lacking: Tapa (penance), Vairagya (dispassion), Sharanagati (surrender).
• Tapas is agreeing with the moment, total acceptance of pleasant or unpleasant situations.
• Vairagya means I want nothing and I am nothing.
• Sharanagati is "I am here for You, for Your joy."

If you are grumbling then these are lacking, because when you accept the situation you cannot grumble; when you take it as Tapa you will not grumble; when you come from a state dispassion ("I don't want anything") you don't grumble; and if you are surrendered you will have no complaints.

All these three (Tapas, Vairagya and Sharanagati) purify your mind and uplift you in joy.

If you don't do it willingly you will do it in desperation. First you say, "Nothing can be done." Then in anger and desperation you say, "I give up, I want nothing, I have no choice, to hell with it!"





Every Stone is Precious


A sculptor in a temple uses all types of stones. Certain stones he uses for the foundations. These never appear outside.

From certain stones which are good to carve, the sculptor makes the walls and pillars of the Temple. From other stones he makes the steps. Certain stones become the tower of the Temple.

Only those stones which are extremely suitable for carving will become the Deity and be installed in the Temple. When the stone become a part of the Temple, it no longer remains a stone, it becomes a sculpture, a piece of art, it becomes the Living Deity.

In the same way many people come to the Master. According to the degree of their surrender they are installed by the Master. All are essential.

If there were no steps, how could a person reach the Temple?

If there were no foundation, how could the Temple be there at all?

What can a tower do without pillars?

For a sculptor, each stone is precious and valuable.






Sensitivity and Strength


Those who are sensitive are often weak. Those who feel themselves strong are often insensitive.
There are some who are sensitive to themselves but insensitive to others. There are some who are sensitive to others but not to themselves.

Those who are sensitive to others often end up feeling "Poor me . . ." Those who are sensitive to themselves often feel, "The others are the bad guys." Some conclude it's better not to be sensitive and they shut off, because sensitivity brings pain. But mind you, if you are not sensitive you will lose all the finer things in life too—intuition, love, joy.

This path and this knowledge make you both strong and sensitive. Often people who are insensitive do not recognize their insensitivity. And those are sensitive often do not recognize their strength. Their sensitivity is their strength.

Sensitivity is intuition; sensitivity is compassion; sensitivity is love.

Sensitivity is strength.

Strength is calmness, endurance, silence, nonreactiveness, confidence, faith—and a smile.
Be both sensitive and strong.






The Golden Veil


Craving comes from encouraging the thought of pleasure. The actual experience of pleasure may not be as pleasurable as the memory.

Question: Is that why we spend so much time in our minds?
Whether you encourage a worldly thought or a Divine thought, they both bring you pleasure. Worldly thought leads to indulgence, which brings you down from pleasure to disappointment and dejection. Divine thought takes you up from pleasure to Bliss, Intelligence, and progress in life. Worldly thought brings pleasure only as memory, whereas Divine thought comes as Reality.

Question: What is a Divine thought?
"I am not the body; I am bliss, satchitananda; I am unbounded space; I am love; I am peace; I am light."

Question: What is a worldly thought?
It is about money, sex, food, power, status and self-image.






Be In The Present Moment

"Be in the present moment. If you live fully now, tomorrow will take care of itself. If you are happy now, the past will not torment you. That is the Art of Living."

Using Google as a Hindi to English dictionary

Recently, an employee at a client’s place was trying to understand an article in Hindi. She came across a word मूल्य वर्धित (Mulya Vardhit) in Hindi. She wanted to know its meaning. Me and other people in the room started guessing and arguing, based on the context, in which the term was used. But no one was sure. Leaving others to guess, I did the following:


Went to Google Indic Transliteration at http://www.google.com/transliterate/indic
Typed in Mulya Vardhit (in English) in the text area. It showed me Mulya Vardhit in Hindi (note that this is transliteration and not translation).
Selected Mulya Vardhit in Hindi, right clicked and selected Copy. Basically copied Mulya Vardhit’s text in Hindi.
Note: The above step saved me from typing in Hindi using a Hindi virtual keyword (for example).
Then I went to Google Translate at http://translate.google.com/translate_t
On the tab “Text and Web”, I pasted (CTRL-V) the hindi text into the text area (labelled as “Original Text”).
From the dropdowns, I selected Hindi >> English.
Clicked on Translate.
I popped up and declared to everyone that “Mulya Vardhit” stands for “Value Added”. The person was reading an article about mobile services and the article was talking about some “value added” servcies.
Obviously there may be other, quicker or better ways to Hindi to English. But this is the Google way