In this post LINQ to XML parse Attribute Values,
we shall see how to parse the values of Attributes from XML tags. In the post LINQ to XML parse XML Elements,
we saw how to extract values from specific elements, here we shall see on how
to extract the values associated with the attributes of the elements.
Assume that we have the following XML fragment
<Employees>
<Employee>
<Name>
<FirstName>Henry</FirstName>
<LastName>Ford</LastName>
</Name>
<Age>65</Age>
<Department Name="Automobile" />
</Employee>
<Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
<Department Name="Software" />
<Department Name="Software" />
</Employee>
</Employees>
Now
we will parse the XML and get the values of the Name attribute in the Department
Tag.
XElement xEmp = XElement.Load(@"D:\Employees.xml");
var empNames = from
emps in xEmp.Elements("Employee")
select
emps;
foreach (XElement
empDetails in empNames)
{
Response.Write("Name:
" + empDetails.Element("Name").Element("FirstName").Value
+ "</br>");
Response.Write("Age:
" + empDetails.Element("Age").Value
+ "</br>");
Response.Write("Department:
" + empDetails.Element("Department").Attribute("Name").Value + "</br></br>");
}
When
this code is executed, the output will be
Name:
Henry
Age: 65
Department: Automobile
Name: Bill
Age: 55
Department: Software
Age: 65
Department: Automobile
Name: Bill
Age: 55
Department: Software
That’s
it we have parsed an XML fragment using LINQ to XML and extracted the attribute
values for the attributes associated with the Element tags.
Related Post
No comments:
Post a Comment