![]() |
Languages »
C / C++ Language »
General
Intermediate
Using XML in C# in the simplest wayBy irfan patelThe sheer power of C# and its ease with XML is displayed here. With zero knowledge, you can just jump into this article and end up learning XML upto the intermediate level. |
C#, XML, Windows, .NET1.0, .NET1.1VS.NET2003, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||

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. :)
Note: You will be demonstrated in Visual Studio .NET but you can create an XML file in literally any text editor.
Note:- It is generally recommended to give an appropriate name wherever required but please follow the instructions as it is, for simplicity.
<?xml version="1.0" encoding="utf-8" ?>
<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> using System;
using System.Xml;
using System.Xml.Schema;
using System.Windows.Forms;
// variable declarations
private string m_sXMLFileName ;
private string m_sSchemaFileName ;
private XmlSchemaCollection m_objXmlSchemaCollection ;
private bool m_bIsFailure=false ;
clsSValidator, paste the following: //We are overloading the constructor
//The following code creates a XmlSchemaCollection object
//this objects takes the xml file's Schema and adds it to its collection
public clsSValidator (string sXMLFileName, string sSchemaFileName)
{
m_sXMLFileName = sXMLFileName;
m_sSchemaFileName = sSchemaFileName;
m_objXmlSchemaCollection = new XmlSchemaCollection ();
//adding the schema file to the newly created schema collection
m_objXmlSchemaCollection.Add (null, m_sSchemaFileName);
}
//This function will Validate the XML file(.xml) against xml schema(.xsd)
public bool ValidateXMLFile()
{
XmlTextReader objXmlTextReader =null;
XmlValidatingReader objXmlValidatingReader=null ;
try
{
//creating a text reader for the XML file already picked by the
//overloaded constructor above viz..clsSchemaValidator
objXmlTextReader = new XmlTextReader(m_sXMLFileName);
//creating a validating reader for that objXmlTextReader just created
objXmlValidatingReader = new XmlValidatingReader (objXmlTextReader);
//For validation we are adding the schema collection in
//ValidatingReaders Schema collection.
objXmlValidatingReader.Schemas.Add (m_objXmlSchemaCollection);
//Attaching the event handler now in case of failures
objXmlValidatingReader.ValidationEventHandler +=
new ValidationEventHandler
(ValidationFailed);
//Actually validating the data in the XML file with a empty while.
//which would fire the event ValidationEventHandler and invoke
//our ValidationFailed function
while (objXmlValidatingReader.Read())
{
}
//Note:- If any issue is faced in the above while it will invoke
//ValidationFailed which will in turn set the module level
//m_bIsFailure boolean variable to false thus returning true as
//a signal to the calling function that the ValidateXMLFile
//function(this function) has encountered failure
return m_bIsFailure;
}
catch (Exception ex)
{
MessageBox.Show ("Exception : " + ex.Message);
return true;
}
finally
{
// close the readers, no matter what.
objXmlValidatingReader.Close ();
objXmlTextReader.Close ();
}
}
ValidateXML
function above.
private void ValidationFailed (object sender, ValidationEventArgs args)
{
m_bIsFailure = true;
MessageBox.Show ("Invalid XML File: " + args.Message);
}
//This will be called only if an the XML file is not in proper format.
//Since it is a file like HTML any one can go and change its format from
//any text editor. So we shud ensure that we are validating it properly.using System;
using System.Windows.Forms;
using System.Xml;
using XMLReadWrite.Classes;
| 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 |
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:
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());
}
}
ReadXMLFileAndFillCombos();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.
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());
}
}
private void cmdWriteToFile_Click(object sender, System.EventArgs e)
{
WriteXMLFileUsingValuesFromCombos();
}
Njoi programming!!
General
News
Question
Answer
Joke
Rant
Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 14 Jul 2004 Editor: Sumalatha K.R. |
Copyright 2004 by irfan patel Everything else Copyright © CodeProject, 1999-2010 Web22 | Advertise on the Code Project |