This article will learn you to read required element and attribute Value from Xml file to a List Object.
See XML File, that I am using for this Example: file.xml
XML file contains list of Airline names with their stops, fares and other information. I've to Read all the Airline Name with Their Fares,Stops and other respective information in a List Object.
See the Code Example:
The above class contains the properties of TopDeals Type that contanis all the required properties.
The Code for reading the Elements Value is below.
In lstData object you will get the all Airlines Name with their other information.
Find the Complete Program : XmlElementReadProgram
See XML File, that I am using for this Example: file.xml
XML file contains list of Airline names with their stops, fares and other information. I've to Read all the Airline Name with Their Fares,Stops and other respective information in a List Object.
See the Code Example:
class TopDeals
{
public string Name { get; set; }
public decimal Price { get; set; }
public string Stops { get; set; }
public string Currency { get; set; }
public List<TopDeals> lstDeals { get; set; }
}
The above class contains the properties of TopDeals Type that contanis all the required properties.
The Code for reading the Elements Value is below.
class Program
{
static void Main(string[] args)
{
XElement root = XElement.Load(@"file.xml");
var rootElem = root.Elements("Airlines").ToList();
TopDeals obj = new TopDeals();
obj.lstDeals = new List<TopDeals>();
foreach (var item in rootElem)
{
TopDeals obj2 = new TopDeals();
obj2.Name = item.Attribute("name").Value;
obj2.Price = Convert.ToDecimal(item.Element("stops").Attribute("Fare").Value);
obj2.Stops = item.Element("stops").Attribute("stop").Value.ToString();
obj2.Currency = item.Element("stops").Attribute("Currency").Value.ToString();
obj.lstDeals.Add(obj2);
}
var lstData = obj.lstDeals.OrderBy(a => a.Price);
}
}
In lstData object you will get the all Airlines Name with their other information.
Find the Complete Program : XmlElementReadProgram
Thanks-
Suraj Kumar
0 comments:
Post a Comment