Pages

Read XML file from C# using Microsoft Visual Studio 2008

Topic says what i'm going to teach you.But first you need to know some theories about XML and C#.
  • System.Xml.XmlDocument class provides handling XML  
  • There are two main .NET APIs for working with XML
  1. XML document object model (DOM) - XmlReader and XmlWriter
  2. Tree Based XML handling
  • XML data loaded into memory.
  • Can search for any node.
What is XML DOM ?
  • It provide standard mechanism for programitically working with data.
Read XML data
  • XML data is load into XmlDocument object
  • So first we have to create a XmlDocument object .

XML data look like this...
<bookstore>
  <book category="CHILDREN">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

Contains root node and multiple child nodes (root node - bookstore)
Each node has the parent node (Except root node)
Each node can have siblings (Except root node).

So if you want to learn XML deeply just go to w3schools.com. There are lot of tutorials available.

OK lets do this. Now we are going to make a new project in Microsoft visual studio 2008 to read a simple XML file.
First you need to launch Visual studio 2008 and Select new Project like this...

After that select Visual C# Windows Forms Application and Give a name to the project and save where ever you want...


Right Click the project and Select Add --> New Folder . Rename that folder into XML.

Right Click the XML folder that you create and Select Add -> New Item . Select XML file and name it as BookStore.xml and Click Add.


Copy and Paste this XML code into BookStore.xml file.

<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
  <book publicationdate="2000" ISBN="212">
    <title>C#</title>
    <author>Author 1</author>
    <price>5000</price>
  </book>
  <book publicationdate="2009" ISBN="312">
    <title>Java for dummies</title>
    <author>Author 2</author>
    <price>12000</price>
  </book>
  <book publicationdate="2008" ISBN="412">
    <title>ASP.NET</title>
    <author>Author 3</author>
    <price>6000</price>
  </book>
</bookstore>

 Now right click the Form1.cs and select view design . Create design like this and rename button name as btnLoad and Text as Load Data.
Also drag and drop a textbox and click the small arrow in the right upper corner and tick the multiline. Change the name as txtresult.



Double click the button and it will automatically direct to the code.
First you need  2 references and a varialble....

using System.Xml;
using System.IO;

 private string _xmlFile;

After that go to the design view and double click the Form1.cs and it will automatically go to code and create Form1_Load event.In the Form1_Load paste this code..
if (!SetxmlFilePath())
            {
                MessageBox.Show("Unable to load  XML file.");
            } 
Now create the private bool SetxmlFilePath() method and paste this code inside that method..
FileInfo fi = new FileInfo(Application.StartupPath + @"\..\..\XML\BookStore.xml");
            if (fi.Exists)
            {
                _xmlFile = fi.FullName;
            }
            else
            {
                return false;
            }
            return true;
 Now goto design area and click the Load button and you will get the btnLoad_click. Inside that paste this code..
DumpContents(_xmlFile);
Now Create private void DumpContents(string _xmlFile) mathod and paste this code inside that method..
           string publishDate = null;
            string title = null;
            string author = null;
            string ISBN = null;
            string price = null;
            XmlElement element = null;

            XmlDocument doc = new XmlDocument();
            doc.Load(_xmlFile);

            foreach (System.Xml.XmlNode node in doc.SelectNodes("//book"))
            {
                title = GetNodeValue(node, "title");
                author = GetNodeValue(node, "author");
                price = GetNodeValue(node, "price");

                element = (XmlElement)node;
                publishDate = element.GetAttribute("publicationdate");
                ISBN = element.GetAttribute("ISBN");

                DisplayBook(title, author, publishDate, ISBN, price);
            }
Create this method..
private void DisplayBook(string title, string author, string publishDate, string ISBN, string price)
        {
            string results = string.Format("{0} ({1}) by {2} (ISBN: {3}), ${4}",title, publishDate, author,
            ISBN, price);
            AddText(results);
        }
After that create AddText methos like this..
private void AddText(string Text)
        {
            txtResult.AppendText(Text + Environment.NewLine);
        }
At last create this method to get the node value
 private string GetNodeValue(XmlNode parentNode, string nodeName)
        {
            string retval = null;

            XmlNode node =parentNode.SelectSingleNode(nodeName);
            if (node != null)
            {
                retval = node.InnerText;
            }
            return retval;
        }
 If you do it correctly right click the project and select build . If there any compilation error you have to fix it to get the result.
If there are no errors click the debug button , after the form shows click the Load Data button and the result textbox shows the xml file.



You can download the sample project
http://hotfile.com/dl/70230733/5270b8d/ReadXML.rar.html


3 comments: