Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / XML
Article

Using XML in C# in the simplest way

Rate me:
Please Sign up or sign in to vote.
3.32/5 (41 votes)
14 Jul 20044 min read 657.7K   10K   90   37
The 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.

Sample Image - XMLReadWrite.jpg

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

  1. Goto File->New->Blank Solution.
  2. Select Visual C# Projects in Project Types.
  3. Select WindowsApplication in Templates.
  4. 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.

  1. Go to menu Project->Add New Item.
  2. 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.

  3. Locate the following line.
    XML
    <?xml version="1.0" encoding="utf-8" ?> 
  4. Below the line, add the following XML piece.
    XML
    <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)

  1. Go to menu XML -> Create Schema.
  2. Notice that in the solution explorer, it has created a file XMLFile1.xsd.
  3. Also notice what the IDE (Integrated Development Environment) has added in <Book> tag of ours.
  4. It signifies our .xml file will be validated against which Schema file.

Creating a class clsSValidator

  1. In the solution explorer, right click the XMLReadWrite project name.
  2. Go to Add-> New Folder and name the folder as Classes.
  3. Now right click the Classes folder name in the solution explorer.
  4. Go to Add-> Add New Item.
  5. Select class and name it as clsSValidator.cls.
  6. This class needs the following namespaces. So paste it on top of the class.
    C#
    using System;
    using System.Xml;
    using System.Xml.Schema;
    using System.Windows.Forms;
    
  7. Just above the constructor, declare the following variables:
    C#
    // variable declarations 
      private string m_sXMLFileName ;
      private string m_sSchemaFileName ;
      private XmlSchemaCollection m_objXmlSchemaCollection ;
      private bool m_bIsFailure=false ;
  8. Below the constructor clsSValidator, paste the following:
    C#
    //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); 
    }
  9. Just below the above code, add the following function:
    C#
    //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 ();
      }
    }
  10. Notice that we are using an event handler in the ValidateXML function above.
  11. Add the following snippet right below it:
    C#
    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.

Reading the values from the XML file

  1. Right click Form1 in Solution Explorer and select View Code.
  2. Replace the namespaces used on the top by the following snippet:
    C#
    using System;
    using System.Windows.Forms;
    using System.Xml;
    using XMLReadWrite.Classes;
  3. Right click Form1 in Solution Explorer and select View Designer.
  4. From the toolbox, place three labels, three comboboxes and one command button as shown in the figure.
  5. Change their properties as following:
    NameProperty Value
    Label1CaptionBook Name
    Label2CaptionRelease Year
    Label3CaptionPublication
    Combo1(Name)cboBookName
     Text[make it blank]
    DropDownStyleDropDownList
    Combo2(Name)cboReleaseYear
    Text[make it blank]
    DropDownStyleDropDownList
    Combo3(Name)cboPublication
    Text[make it blank]
     DropDownStyleDropDownList
    Button1 (Name)cmdWriteToFile
     Text&Write To File
  6. 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:

  7. Just above the Load event paste the following code:
    C#
    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());
      }
    }
  8. Now in the load event paste the following to call this method:
    C#
    ReadXMLFileAndFillCombos();
    

Writing the values to the XML file

  1. Now right click the form1 again in solution explorer and go to its designer.
  2. 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.

  3. Just above the click event paste the following snippet:
    C#
    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());
      }
    }
  4. Now we have to call this method from the click event of the button. So make it look like the following:
    C#
    private void cmdWriteToFile_Click(object sender, System.EventArgs e)
    {
      WriteXMLFileUsingValuesFromCombos();
    }
  5. Run it to see its beauty ;)

Njoi programming!!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Instructor / Trainer
India India
Irfan Patel is a Bachelor of Computer Application
He holds a MCSD, MCP.NET, ITIL Certifications and has worked extensively with C#, ASP.Net, SQL Server since 1998.
He has also trained various programming languages and tools, RDBMS & OS platforms to more than 1000 students.

His expertise comes from various industries viz Jewellery, Shipping ,Automobiles , RFID projects, Ticket Reservation systems and e-commerce websites.

Besides teaching and programming he loves music, singing, dancing, bikes & following his favourite football team Chelsea.

Comments and Discussions

 
QuestionMingled with VB code Pin
Member 1231487119-Apr-17 3:25
Member 1231487119-Apr-17 3:25 
Question.cls file in a C# project ? Pin
SEWong20-Jul-14 11:36
SEWong20-Jul-14 11:36 
GeneralMy vote of 3 Pin
sadmonew29-May-14 20:38
sadmonew29-May-14 20:38 
GeneralRe: My vote of 3 Pin
tomicrow11-Jun-14 19:24
tomicrow11-Jun-14 19:24 
GeneralMy vote of 4 Pin
Omprakash Kukana18-Nov-13 21:24
Omprakash Kukana18-Nov-13 21:24 
QuestionThanks! Pin
Mr.thang31-Jul-13 17:47
Mr.thang31-Jul-13 17:47 
GeneralHelp.... Pin
asik00098-Jul-12 0:27
asik00098-Jul-12 0:27 
QuestionHi Irfan Patel! Pin
smartboy7865-Jun-12 3:14
smartboy7865-Jun-12 3:14 
GeneralMy vote of 2 Pin
squirly48-Dec-11 17:21
squirly48-Dec-11 17:21 
Generalusing xml in c# in simplest way Pin
amitrajahuja29-Jan-11 4:42
amitrajahuja29-Jan-11 4:42 
GeneralHi, please dont post something unless it works Pin
wrecking ball8-Jul-10 17:41
wrecking ball8-Jul-10 17:41 
GeneralXML Articles Pin
ChizI13-Jan-10 4:54
ChizI13-Jan-10 4:54 
General[My vote of 1] My vote for 1 Pin
catennacio3-Aug-09 13:13
catennacio3-Aug-09 13:13 
GeneralMy vote of 1 Pin
Navin Pandit12-Jul-09 19:56
Navin Pandit12-Jul-09 19:56 
GeneralMy vote of 1 Pin
Paolo Vernazza8-Jul-09 3:35
Paolo Vernazza8-Jul-09 3:35 
GeneralMy vote of 2 Pin
Mark Pryce-Maher8-Apr-09 5:02
Mark Pryce-Maher8-Apr-09 5:02 
Generalhello Pin
Alex Manolescu21-Jan-09 12:09
Alex Manolescu21-Jan-09 12:09 
GeneralMaybe Im having a dumb day... Pin
supermankelly6-Aug-08 6:10
supermankelly6-Aug-08 6:10 
AnswerRe: Maybe Im having a dumb day... Pin
Member 46375998-Sep-08 8:16
Member 46375998-Sep-08 8:16 
QuestionProblem with XSD HELP Pin
w3iling8-Nov-07 4:42
w3iling8-Nov-07 4:42 
GeneralDoubt! [modified] Pin
Kumar!13-Sep-07 21:12
Kumar!13-Sep-07 21:12 
Generalredundancy Pin
kaustuvdebiswas17-Aug-06 13:14
kaustuvdebiswas17-Aug-06 13:14 
Generalxsl Pin
JacquesDP12-Jan-06 18:44
JacquesDP12-Jan-06 18:44 
GeneralXML namespace Pin
Anonymous3-Jun-05 9:22
Anonymous3-Jun-05 9:22 
GeneralC++ namespace Pin
Anonymous3-Jun-05 9:17
Anonymous3-Jun-05 9:17 
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. Big Grin | :-D

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.