Tuesday 28 February 2012

XML File reading Using XDocument in C#


Adding XML to Solution

1.       Right Click on Project
2.       Add
3.       New Item
4.       Select  XMLFile1.xml
5.       Right Click on created XML File
6.       Properties
7.        Set Build Action as “Embedded Resource”  (how the files relates to the build and deployment processes)

Sample XML 

<?xml version="1.0" encoding="utf-8" ?>

 <Books>

  <Book ID="1">
    <Name>Poohambam</Name>
    <Author>Mr Aasim Alavi</Author
    <Price>150</Price>    
  </Book>

<Book ID="2">
    <Name>C#</Name>
    <Author>Nick Wienholt</Author
    <Price>2300</Price>    
  </Book>
   
</Books>

Reading 

Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("TestProject.Books.xml");


            if (stream == null)
                return;
            XDocument data = XDocument.Load(stream);

foreach (XElement book in data.Root.Nodes())
{
        // TO DO :
        //int bookID = Convert.ToInt32(book.Attribute("ID").Value);
        //string bookName = book.Element("Name").Value;
        //decimal price = Convert.ToDecimal(book.Element("Price").Value);                 
}




1 comment: