Section67.1:ReadXMLusingLINQtoXML
<?xmlversion=”1.0″encoding=”utf-8″?>
<Employees>
<Employee>
<EmpId>1</EmpId>
<Name>Sam</Name>
<Sex>Male</Sex>
<PhoneType=”Home”>423-555-0124</Phone>
<PhoneType=”Work”>424-555-0545</Phone>
<Address>
<Street>7ACoxStreet</Street>
<City>Acampo</City>
<State>CA</State>
<Zip>95220</Zip>
<Country>USA</Country>
</Address>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Name>Lucy</Name>
<Sex>Female</Sex>
<PhoneType=”Home”>143-555-0763</Phone>
<PhoneType=”Work”>434-555-0567</Phone>
<Address>
<Street>JessBay</Street>
<City>Alta</City>
<State>CA</State>
<Zip>95701</Zip>
<Country>USA</Country>
</Address>
</Employee>
</Employees>
ToreadthatXMLfileusingLINQ
XDocumentxdocument=XDocument.Load(“Employees.xml”); IEnumerable<XElement>employees=xdocument.Root.Elements();
foreach(varemployeeinemployees)
{
Console.WriteLine(employee);
}
Toaccesssingleelement
XElementxelement=XElement.Load(“Employees.xml”); IEnumerable<XElement>employees=xelement.Root.Elements();
Console.WriteLine(“Listof allEmployeeNames :”);
foreach(varemployeeinemployees)
{
Console.WriteLine(employee.Element(“Name”).Value);
}
Toaccessmultipleelements
XElementxelement=XElement.Load(“Employees.xml”);
IEnumerable<XElement>employees = xelement.Root.Elements(); Console.WriteLine(“ListofallEmployeeNamesalongwiththeirID:”);
foreach(varemployeeinemployees)
{
Console.WriteLine(“{0} has Employee ID {1}”,
employee.Element(“Name”).Value,
employee.Element(“EmpId”).Value);
}
ToaccessallElementshavingaspecificattribute
XElementxelement=XElement.Load(“Employees.xml”);
varname=fromnminxelement.Root.Elements(“Employee”) where(string)nm.Element(“Sex”)==”Female”selectnm;
Console.WriteLine(“DetailsofFemaleEmployees:”);
foreach(XElementxEleinname) Console.WriteLine(xEle);
Toaccessspecificelementhavingaspecificattribute
XElementxelement=XElement.Load(“..\\..\\Employees.xml”);
varhomePhone=fromphonenoinxelement.Root.Elements(“Employee”)
where(string)phoneno.Element(“Phone”).Attribute(“Type”)==”Home”selectphoneno;
Console.WriteLine(“ListHomePhoneNos.”);
foreach(XElementxEleinhomePhone)
{
Console.WriteLine(xEle.Element(“Phone”).Value);
}
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter98:Networking 28/04/2024
- Chapter97:FileandStreamI/O 27/04/2024
- Chapter96:Delegates 26/04/2024