I am trying to get all the nodes from an xml file, but I cannot get the node having attributes such as Home and Work. Well, in my case I can get phone Home but not phone Work. Thank you.
This is the xml file structure:
<Employees>
<Employee>
<EmpId>1</EmpId>
<Name>Sam</Name>
<Sex>Male</Sex>
<Phone Type="Home">423-555-0124</Phone>
<Phone Type="Work">424-555-0545</Phone>
<Address>
<Street>7A Cox Street</Street>
<City>Acampo</City>
<State>CA</State>
<Zip>95220</Zip>
<Country>USA</Country>
</Address>
</Employee>
</Employee>
This is my code in C#:
XElement xelement = XElement.Load("employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
Console.WriteLine("List of all Employee Names along with their ID:");
foreach (var employee in employees)
{
employee.Element("EmpId").Value);
Console.WriteLine("SEX: {0}", employee.Element("Sex").Value);
Console.WriteLine("Home: {0}", employee.Element("Phone").Value);
Console.WriteLine("Work: {0}\n", employee.Element("Phone").Value);
}
Result:
Wished:
You need to use the Attribute
method to get at an attribute. You'll need to query for Phone
elements with a Type
attribute of Home
. For example:
Console.WriteLine("Home: {0}",
employee.Elements("Phone")
.Single(x => x.Attribute("Type").Value == "Home")
.Value);
You should think about what you want to do if there isn't a phone number for the type you want, or if there are multiple ones. (The Single
method requires exactly one match. There's also First
and Last
, as well as FirstOrDefault
or LastOrDefault
, which will return null
if there are no matches.)
See more on this question at Stackoverflow