|

Introduction
Like HTML, XML is made for the World Wide Web but the set of tags are not
fixed. They can be extended and hence the name. We can have our own tags. The
only thing we have to do is to maintain a structural relationship between them.
It's written in SGML (Standard Generalized Markup Language) which is an
international standard for defining descriptions across the globe.
XML was developed way back in 1996 by an XML Working Group (known originally
as the SGML Editorial Review Board) which was formed under the guidance of the
World Wide Web Consortium (W3C) which was chaired by Jon Bosak of Sun
Microsystems. But, B-U-T, but many of us in spite of being in IT, still do not
know much about XML. Like my previous article, even this one assumes the reader
to be a beginner (or intermediate) to help you know even some hidden facts.
Getting late!! Let's get back to work first!!
To start with, just follow the instructions step by step. Thanks in advance
for your co-operation. :)
Step By Step Walkthrough
- Goto File->New->Blank Solution.
- Select Visual C# Projects in Project Types.
- Select WindowsApplication in Templates.
- Type for eg., XMLReadWrite in the Name textbox.
Creating an XML file (the data file which will be read by our
application)
Note: You will be demonstrated in Visual Studio .NET but you can
create an XML file in literally any text editor.
- Go to menu Project->Add New Item.
- In the dialog box select XMLFile and click Open.
Note:- It is generally recommended to give an appropriate name wherever
required but please follow the instructions as it is, for simplicity.
- Locate the following line.
="1.0" ="utf-8"
- Below the line, add the following XML piece.
<Book>
<BookName>C# Professional</BookName>
<BookName>C# Cookbook</BookName>
<BookName>SQL Server Black Book</BookName>
<BookName>Mastering VB.Net</BookName>
<BookName>ASP.Net Unleashed</BookName>
<BookName>.Net Framework Essentials</BookName>
<ReleaseYear>2001</ReleaseYear>
<ReleaseYear>2002</ReleaseYear>
<ReleaseYear>2003</ReleaseYear>
<ReleaseYear>2004</ReleaseYear>
<Publication>EEE</Publication>
<Publication>Microsoft Press</Publication>
<Publication>O 'Reilly</Publication>
<Publication>BpB</Publication>
<Publication>Sams TechMedia</Publication>
</Book>
Creating the schema (.XSD) file for validating our just made .xml
file)
- Go to menu XML -> Create Schema.
- Notice that in the solution explorer, it has created a file XMLFile1.xsd.
- Also notice what the IDE (Integrated Development Environment) has added in
<Book> tag of ours.
- It signifies our .xml file will be validated against which Schema
file.
Creating a class clsSValidator
- In the solution explorer, right click the XMLReadWrite project name.
- Go to Add-> New Folder and name the folder as Classes.
- Now right click the Classes folder name in the solution explorer.
- Go to Add-> Add New Item.
- Select class and name it as clsSValidator.cls.
- This class needs the following namespaces. So paste it on top of the class.
using System;
using System.Xml;
using System.Xml.Schema;
using System.Windows.Forms;
- Just above the constructor, declare the following variables:
private string m_sXMLFileName ;
private string m_sSchemaFileName ;
private XmlSchemaCollection m_objXmlSchemaCollection ;
private bool m_bIsFailure=false ;
- Below the constructor
clsSValidator, paste the following:
public clsSValidator (string sXMLFileName, string sSchemaFileName)
{
m_sXMLFileName = sXMLFileName;
m_sSchemaFileName = sSchemaFileName;
m_objXmlSchemaCollection = new XmlSchemaCollection ();
m_objXmlSchemaCollection.Add (null, m_sSchemaFileName);
}
- Just below the above code, add the following function:
public bool ValidateXMLFile()
{
XmlTextReader objXmlTextReader =null;
XmlValidatingReader objXmlValidatingReader=null ;
try
{
objXmlTextReader = new XmlTextReader(m_sXMLFileName);
objXmlValidatingReader = new XmlValidatingReader (objXmlTextReader);
objXmlValidatingReader.Schemas.Add (m_objXmlSchemaCollection);
objXmlValidatingReader.ValidationEventHandler +=
new ValidationEventHandler
(ValidationFailed);
while (objXmlValidatingReader.Read())
{
}
return m_bIsFailure;
}
catch (Exception ex)
{
MessageBox.Show ("Exception : " + ex.Message);
return true;
}
finally
{
objXmlValidatingReader.Close ();
objXmlTextReader.Close ();
}
}
- Notice that we are using an event handler in the
ValidateXML
function above.
- Add the following snippet right below it:
private void ValidationFailed (object sender, ValidationEventArgs args)
{
m_bIsFailure = true;
MessageBox.Show ("Invalid XML File: " + args.Message);
}
Reading the values from the XML file
- Right click Form1 in Solution Explorer and select View Code.
- Replace the namespaces used on the top by the following snippet:
using System;
using System.Windows.Forms;
using System.Xml;
using XMLReadWrite.Classes;
- Right click Form1 in Solution Explorer and select View Designer.
- From the toolbox, place three labels, three comboboxes and one command
button as shown in the figure.
- Change their properties as following:
| Name |
Property |
Value |
Label1 |
Caption |
Book Name |
Label2 |
Caption |
Release Year |
Label3 |
Caption |
Publication |
Combo1 |
(Name) |
cboBookName |
| |
Text |
[make it blank] |
|
DropDownStyle |
DropDownList |
Combo2 |
(Name) |
cboReleaseYear |
|
Text |
[make it blank] |
|
DropDownStyle |
DropDownList |
Combo3 |
(Name) |
cboPublication |
|
Text |
[make it blank] |
| |
DropDownStyle |
DropDownList |
Button1 |
(Name) |
cmdWriteToFile |
| |
Text |
&Write To File |
- Double click on the form (not on any other controls area) to open its
Load event.
Note: XmlTextReader (Namespace:- System.Xml) is
used in our code below. It gives a read-only forward only access. This class
helps us to read XML from stream or file with a very important feature of
skipping unwanted data from it. Check out our usage below:
- Just above the
Load event paste the following code: private void ReadXMLFileAndFillCombos()
{
try
{
string sStartupPath = Application.StartupPath;
clsSValidator objclsSValidator =
new clsSValidator(sStartupPath + @"..\..\..\XMLFile1.xml",
sStartupPath + @"..\..\..\XMLFile1.xsd");
if (objclsSValidator.ValidateXMLFile()) return;
XmlTextReader objXmlTextReader =
new XmlTextReader(sStartupPath + @"..\..\..\XMLFile1.xml");
string sName="";
while ( objXmlTextReader.Read() )
{
switch (objXmlTextReader.NodeType)
{
case XmlNodeType.Element:
sName=objXmlTextReader.Name;
break;
case XmlNodeType.Text:
switch(sName)
{
case "BookName":
cboBookName.Items.Add(objXmlTextReader.Value);
break;
case "ReleaseYear":
cboReleaseYear.Items.Add(objXmlTextReader.Value);
break;
case "Publication":
cboPublication.Items.Add(objXmlTextReader.Value);
break;
}
break;
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
- Now in the load event paste the following to call this method:
ReadXMLFileAndFillCombos();
Writing the values to the XML file
- Now right click the form1 again in solution explorer and go to its designer.
- Double click the command button to see its
Click event.
Note: XmlTextWriter (Namespace: System.Xml) is
used in our code below. This class helps us to write XML on many places like
stream, console, file etc. We are pushing the XML on a file. Simply nest the
Start and End method and it's done.
- Just above the click event paste the following snippet:
private void WriteXMLFileUsingValuesFromCombos()
{
try
{
string sStartupPath = Application.StartupPath;
XmlTextWriter objXmlTextWriter =
new XmlTextWriter(sStartupPath + @"\selected.xml",null);
objXmlTextWriter.Formatting = Formatting.Indented;
objXmlTextWriter.WriteStartDocument();
objXmlTextWriter.WriteStartElement("MySelectedValues");
objXmlTextWriter.WriteStartElement("BookName");
objXmlTextWriter.WriteString(cboBookName.Text);
objXmlTextWriter.WriteEndElement();
objXmlTextWriter.WriteStartElement("ReleaseYear");
objXmlTextWriter.WriteString(cboReleaseYear.Text);
objXmlTextWriter.WriteEndElement();
objXmlTextWriter.WriteStartElement("Publication");
objXmlTextWriter.WriteString(cboPublication.Text);
objXmlTextWriter.WriteEndElement();
objXmlTextWriter.WriteEndElement();
objXmlTextWriter.WriteEndDocument();
objXmlTextWriter.Flush();
objXmlTextWriter.Close();
MessageBox.Show("The following file has been successfully created\r\n"
+ sStartupPath
+ @"\selected.xml","XML",MessageBoxButtons.OK,
MessageBoxIcon.Information );
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
- Now we have to call this method from the click event of the button. So make
it look like the following:
private void cmdWriteToFile_Click(object sender, System.EventArgs e)
{
WriteXMLFileUsingValuesFromCombos();
}
- Run it to see its beauty ;)
Njoi programming!!
| You must Sign In to use this message board. |
|
| | Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh) | FirstPrevNext |
|
|
 |
|
|
But this below step i can't follow.. Im new to Visual C# 2008 which I am using... where is XML menu? (XML> Create Schema)
Creating the schema (.XSD) file for validating our just made .xml file) Go to menu XML -> Create Schema. Notice that in the solution explorer, it has created a file XMLFile1.xsd. Also notice what the IDE (Integrated Development Environment) has added in <Book> tag of ours. It signifies our .xml file will be validated against which Schema file.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I'm using Visual C# 2005 and I'm having the same problem. The XML menu is only found in Visual Studio, not the express edition. I know this can be done in a much easier way, but I can't remember how. 
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
i am using visual c# 2005 while creating the xsd file once i click on create schema on solution exploreer there is no xsd file ceated on the from itself it shows
what shd i do now urgent
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Hai irfan! Thanks for your article, really going to help me a lot! What is the use of validation here! Can u please explain it, i have some doubt with that! also explain me whether it will validate against attributes or elements? because in my project i am using length as one of the attribute, how to check this length that agains my input for that particulat node? i have no option to create schme, if i give add new item ->xml schema then it will give new schma, but i want to get the schema for our xml file, how could i do that? please help me! i dont have the XMl menu in my .NET IDE. how could i get this? please help me!
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thanks for the example. A question however - I dont understand why you are reading the same xml file twice? once for reading/validating it and then again for reading it. any particular reasons? wouldnt it be less time expensive if the validator passed back a reader object if the validation was successful.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
My question doesn't really have impact on this article but for the fact that it is about xml. i'm quite new to xml so still figuring out babysteps.:->
using c# i'm witing data to xml with the xmltextwriter class. then using xsl stylesheet i view the data via html.
all i still need to do is add one tag. <?xml:stylesheet type="text/xsl" href=""?> this must be done via c#, is there a way i do this via the xmltextwriter or do i need to do something else.
Any help wil be appreciated.
Thanx in advance.
-- modified at 0:45 Friday 13th January, 2006
|
| Sign In·View Thread·PermaLink | 3.50/5 (2 votes) |
|
|
|
 |
|
|
Personally, I think this is a very bad article for beginners. It looks like you are not very familiar with either C# or XML.
The article code is hard to read and is not the proper way to be accomplishing the goals here.
I've been programming XML for 3 years and C# for 1 1/2 years and I'm confused.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hey...
I noticed some people critiquing your XML skills. I've decided to critique your C# skills.
Gone are the days of using m_ to prefix member variables. Instead you should use something like
public void Test( string TestVariable ) { this.TestVariable = TestVariable; }
You do not need to prefix object instances with Obj since everything in C# is derived from System.Object. Instead, you can prefix with something more reader friendly such as...
XmlDocument MyXmlDocument = new XmlDocument( );
or....
XmlDocument BooksXml = new XmlDocument( );
There is a truth about speaking the language of the land.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hello there,
Thanx for your article, it put me on the right track, but an important yet crucial piece of information in missing :
In your xml root node you should specify 'xmlns="targetNameSpace"', where targetNameSpace has the same value of the 'targetNamespace=""' specified in the root of the xsd used. If you don't to this everything validation you do seems fine, always !!
Another problem with your code is that in the finally block you close all used reader without checking them first to be different from null, meaning that your finally block itself would throw an 'object null reference exception'.
The next time be a bit more strict, it's needed in programming 
Erlend Robaye
Fluxys N.V. Belgium Erland.Robaye@fluxys.net
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
There are so many tools that claim to be OBJECT Oriented, it is getting out of hand to be able to know the good from the bad and ugly.
XML is certainly a good thing, but which too to use to develop OOC and which other languages to use: C++, Java, etc.
What is the role of UML when developing using XML. Do you need UML? I am certainly confused!!!!!!!!!!!!!!!!
I will be glad to participate in forums related to Software Modeling, Simulation, Code Generation, and Reverse Engineering
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
You should never rely on items being stored in any particular order in XML as you do in this article. By doing so you are only asking for problems. Instead of writing the file as:
<Book> <Title>Title A</Title> <Title>Title B</Title> <ReleaseDate>2004</ReleaseDate> <ReleaseDate>2002</ReleaseDate> etc... etc.. etc... </Book>
you should be doing this:
<Books> <Book> <Title>Title A</Title> <ReleaseDate>2004</ReleaseDate> </Book> <Book> <Title>Title B</Title> <ReleaseDate>2002</ReleaseDate> </Book> etc...etc... etc... </Books>
you can then select out each book node by using SelectNodes(...) and XPath notation, and then iterate over the result collection to read the data.
-mdb
|
| Sign In·View Thread·PermaLink | 4.69/5 (5 votes) |
|
|
|
 |
|
|
Apart from this xml representation of data, over-all he tackle the xml-subject nicely, especially for the beginners!.. We should encourage new commers, atleast they have the courage to publish something... Good Job Patel
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Sonia Gandhi wrote: Apart from this xml representation of data, over-all he tackle the xml-subject nicely, especially for the beginners!.. We should encourage new commers, atleast they have the courage to publish something... Good Job Patel
Sonia - you are totally wrong on the 'especially for beginners'. Beginners should be taught the RIGHT way to do things, not the WRONG way. This article presents the WRONG way. This will only lead to confusing them about the purposes and capabilities of XML. Its like teaching beginning math students that parentheses in math equations are just there to make them look nicer.
Patel - I'm glad you are willing to submit articles. Thanks for this - I haven't submitted even one so you are one up on me in this category. I can only assume that the source of this particular article came from your personal experience and how you use XML. Let me just say that you are not using it the way it was intended - you might as well be using your own custom file format.
-mdb
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hey guys!! This is Irfan Patel. Thanx for your criticism fuzzylintman. True I have undermined XML but thats what I intended to do. XML is something very powerful and complex for that matter specially for beginners and my article was for beginners. Inspite of having 6yrs in development experience I spent days to figure out what is what!!! Thats the reason I took the simplest XML example of only two layers deep which as you have said truly undermined the power of XML. Thanx fuzzylintman for encouraging me to write BETTER  And thanx sonia for encouraging me to write MORE !! 
Irfan Patel (MCSD) Technical Architect New Mumbai, India
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Irfan, I understand XML fine, but new to C#. When I pull your downloaded project in I have not problem. But when I build from scratch, it does not build correctly with identical code. I have problem getting to Classes folder see below for reference. Please help in setup or what I need to work properly. Thanks-alex
C:\Documents and Settings\alex\My Documents\Visual Studio Projects\XMLReadWrite_alex\Form1.cs(4): The type or namespace name 'Classes' does not exist in the class or namespace 'XMLReadWrite_alex' (are you missing an assembly reference?)
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
Dear Alex, Yes there is a quite visible error. Looking at your message I can make out that it is the Namespace which is harassing you. You have chosen a namespace 'XMLReadWrite_alex' and the source code I have attached has 'XMLReadWrite'. Hence if you try to access the classes folder you have to give 'XMLReadWrite_alex.Classes' as the namespace. Hope it suffice your needs.
Irfan Patel (MCSD) Technical Architect New Mumbai, India
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
Hey, I am new to XML in regards to development, but have had to handle them for support reasons. I do have to say i did scratch my head at the read XML format and agree it could casue confusion and bad development habits. Why is always good to read these comments before starting like I am!
I understand patel is trying to keep things simple, which is good. And maybe stick with this approach as these type of tutorials i need! but perhaps in situations like this have a post note or section explaining important facts like this. As by the point (after tutorial) they are ready for the more complex information.
Andrew
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
The idea of generating classes from XML schemas and then programming using those classes just about eliminates the dramatic polymorphism that XML allows. Yes, if member nodes/attributes/methods/whatever are named and programmed for orthogonally (sp?) in the application, it can be achieved, but few programmers take advantage of it in their applications. One of the true beauties of XML structure is its allowance for lower-level functions (OK, methods if you prefer) to know nothing about the data upon which it is operating, which has a ripple effect to the higher levels of the application. The net (no pun intended) effect is that application layers can do a lot of work without concern for the particular node or "class" they are acting upon, which reduces code size and complexity. But, alas, sadly, few programmers using formal object-oriented programming languages understand how to apply polymorphism anyway.
|
| Sign In·View Thread·PermaLink | 2.00/5 (2 votes) |
|
|
|
 |
|
|
i gotta agree with this... the xml schema is pretty terrible irfan. basically i'll feel sorry for any beginner who doesnt know anything about xml comng here and reading that. and its a shame that its so high up in teh search engien results.
irfan could you correct this article please? a lot of people seem to be finding problems with it and i take great offence to the xml schema on top since i can guess it would be pretty influential for someoen whos learning xml.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|