LINQ to read XML

Loading the XML File

XElement and XDocument derive from XContainer.

1. XElement class

Reads the XML elements (attributes and children)

Implements IXmlSerializable.

XElement xelement = XElement.Load(file);
IEnumerable employees = xelement.Elements();
//Read the entire XML
foreach(var employee in employees)
{
	Console.WriteLine("Reading Employee: == " + employee);
}

2. XDocument class

Reads the entire XMl document.

Reads from the single root element.

XDocument xdocument = XDocument.Load(file);
IEnumerable employees = xdocument.Elements();
foreach(var employee in employees)
{
     Console.WriteLine("Reading Employee: == " + employee);
}

Reading the Single Element

foreach(var employee in employees)
{
     Console.WriteLine("Reading Employee: == " + employee.Element("Name").Value);
}

Reading Multiple Elements

foreach(var employee in employees)
{
Console.WriteLine("Reading Employee: {0} == {1}", employee.Element("Name").Value, employee.Element("EmpId").Value);
}

Filter Elements

XElement xelement = XElement.Load(file);
var name = from nm in xelement.Elements("Employee")
    where (string)nm.Element("Sex") == "Female"
    select nm;

    Console.WriteLine("Information about Female Employees");
    foreach(XElement x in name)
    {
	Console.WriteLine(x);
    }

Filter Element within another Element

XElement xelement = XElement.Load(file);
var addresses = from address in xelement.Elements("Employee")
	where (string)address.Element("Address").Element("City") == "Alta"
	select address;

Console.WriteLine("Information about Employees in Alta City");
foreach(XElement x in addresses)
{
	Console.WriteLine(x);
}

Find Nested Elements using Descendants

XElement xelement = XElement.Load(file);
Console.WriteLine("List of all Zip codes");
foreach(XElement x in xelement.Descendants("Zip"))
{
    Console.WriteLine((string)x);
}

Sorting Elements

XElement xelement = XElement.Load(file);
IEnumerable codes = from code in xelement.Elements("Employee")
	let zip = (string)code.Element("Address").Element("Zip")
        orderby zip
	select zip;
Console.WriteLine("List and Sort all Zip Codes");
			 
foreach (string zp in codes)
	Console.WriteLine(zp);

Leave a Reply

Your email address will not be published. Required fields are marked *