This example is really simple.
The taks is to get the books from the XML.
What I did.
1 - I created a internal class called Book.
2 - A declaration of a list of books
3 - The XML we're gonna use.
4 - Instantiating the XMLDocument class.
5 - LoadXML
6 - Using the method GetElementsByTagName. Very usefull to get lists inside XMLs.
7 - A for to go through the items. It's weird that ChildNodes is after Item(0), but that's the way it is.
8 - Each item is a node of nodes. To access each node of a item, you have to use SelectSingleNode.
9 - Fill the class object with the Nodes' values.
10 - Fill the list of books.
11 - End.
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Data;
using System.Collections;
namespace ConsoleApplication1
{
/// <summary>
///
/// </summary>
class Program
{
class Book
{
public Int32 Number = 0;
public string Name = "";
public Decimal Price = 0.0M;
}
static void Main(string[] args)
{
List<Book> lstBooks = new List<Book>();
string lStrXML = "";
lStrXML += "<Library>";
lStrXML += "<Address type='String'>Washington D.C.</Address>";
lStrXML += "<Books>";
lStrXML += "<item>";
lStrXML += "<Number type='Integer'>1</Number>";
lStrXML += "<Name type='String'>The Game Of Thrones</Name>";
lStrXML += "<Price type='Decimal'>7.0</Price>";
lStrXML += "</item>";
lStrXML += "<item>";
lStrXML += "<Number type='Integer'>2</Number>";
lStrXML += "<Name type='String'>Dune</Name>";
lStrXML += "<Price type='Decimal'>4.0</Price>";
lStrXML += "</item>";
lStrXML += "<item>";
lStrXML += "<Number type='Integer'>3</Number>";
lStrXML += "<Name type='String'>The Mists Of Avalon</Name>";
lStrXML += "<Price type='Decimal'>6.0</Price>";
lStrXML += "</item>";
lStrXML += "</Books>";
lStrXML += "</Library>";
XmlDocument lobj = new XmlDocument();
lobj.LoadXml(lStrXML);
XmlNodeList lObjBooks = lobj.GetElementsByTagName("Books");
foreach (XmlNode lObjXBook in lObjBooks.Item(0).ChildNodes)
{
Book lObjBook = new Book();
Int32.TryParse(lObjXBook.SelectSingleNode("Number").InnerText, out lObjBook.Number);
lObjBook.Name = lObjXBook.SelectSingleNode("Name").InnerText;
Decimal.TryParse(lObjXBook.SelectSingleNode("Price").InnerText, out lObjBook.Price);
lstBooks.Add(lObjBook);
}
}
}
}