Thursday, September 3, 2009

How to read XML data using C#

You can read XML data from the file using C#. Lets start with the solution...
Suppose XmlData.xml is the xml file with the following data,




Now the C# code for reading the data from the file is as shown below,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Data;

namespace DashBoardDatabaseLayer
{
public class XMLClass
{
public DataTable GetXmlData()
{
string dataPath = @"PATH OF THE XML FILE";
var doc = XDocument.Load(dataPath + "NAME OF THE XML FILE");

DataTable XmlDataTable = new DataTable();
XmlDataTable.Columns.Add("Project Name", typeof(string));
XmlDataTable.Columns.Add("Project Desc", typeof(string));
XmlDataTable.Columns.Add("Start Date", typeof(string));
XmlDataTable.Columns.Add("End Date", typeof(string));
XmlDataTable.Columns.Add("Plan Complete", typeof(bool));
XmlDataTable.Columns.Add("Design Complete", typeof(bool));
XmlDataTable.Columns.Add("Code Complete", typeof(bool));
XmlDataTable.Columns.Add("Testing Complete", typeof(bool));
XmlDataTable.Columns.Add("UAT Complete", typeof(bool));
XmlDataTable.Columns.Add("Defects", typeof(int));
XmlDataTable.Columns.Add("Efforts", typeof(int));
var query = from c in doc.Elements("projects").Elements("project") select c;
foreach (XElement project in query)
{
XmlDataTable.Rows.Add(project.Attribute("Name").Value, project.Elements("description").First().Value,
project.Elements("startdate").First().Value, project.Elements("enddate").First().Value, Convert.ToBoolean(project.Elements("planningcomplete").First().Value),
Convert.ToBoolean(project.Elements("designcomplete").First().Value), Convert.ToBoolean(project.Elements("codingcomplete").First().Value), Convert.ToBoolean(project.Elements("testingcomplete").First().Value),
Convert.ToBoolean(project.Elements("uatcomplete").First().Value), Convert.ToInt32(project.Elements("defects").First().Value), Convert.ToInt32(project.Elements("efforts").First().Value));
}
return XmlDataTable;
}
}
}


Now, using this code u will be able to extract data from the XML file.
And this is for free, hence it is Fukat ka Gyan !

2 comments:

  1. XmlTextReader provides direct parsing and tokenizing of XML and implements the XML 1.0 specification as well as the namespaces in the XML specification from the World Wide Web Consortium (W3C). This article provides fast, tokenized stream access to XML rather than using an object model such as the XML Document Object Model (DOM).STC Technologies|STC Technologies

    ReplyDelete
  2. Hii you are providing good information.Thanks for sharing The Best Hardware and Networking Institute in Hyderabad from RCP Technologies with Industry experts. See below link

    hardware-and-networking training

    ReplyDelete