如何使用LINQ to XML获取属性值?

Cha*_*u A 11 c# xml linq linq-to-xml

<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>
  </Employee>
</Employees>
Run Code Online (Sandbox Code Playgroud)
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    emplyeeDetails = XDocument.Load(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\LinqToXml\\Xmls\\" + "Employees.xml");
    var emplyees = from emp in emplyeeDetails.Descendants("Employee").Take(10)
                   orderby emp.Element("EmpId").Value ascending
                   select new
                   {
                       Id = emp.Element("EmpId").Value,
                       Name = emp.Element("Name").Value,
                       Sex = emp.Element("Sex").Value,
                       WorkPhone=emp.Element("Phone").Attribute("Type").Value,
                       HomePhone = emp.Element("Phone").Attribute("Type").Value,                               
                   };
    DgrdEmployeeDetails.ItemsSource = emplyees.ToList();
}
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,我可以得到以下结果: 在此输入图像描述

但我需要列WorkPhone的值424-555-0545而不是HomeHomePhone的值423-555-0124而不是列的值Home.

我该怎么办?

Céd*_*non 14

使用Where方法:

对于家庭电话号码:

emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Home").Value
Run Code Online (Sandbox Code Playgroud)

对于工作电话号码:

emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Work").Value
Run Code Online (Sandbox Code Playgroud)
  • emp.Elements("Phone")是所有"电话"元素的可枚举emp.
  • Single 将获得满足指定属性的元素(如果有0个或多个元素满足该属性,则会引发错误).
  • phoneElement.Attribute("Type").Value 是"类型"属性的值(即"主页"或"工作")

然后,您的代码应该是:

var emplyees = from emp in emplyeeDetails.Descendants("Employee").Take(10)
                orderby emp.Element("EmpId").Value ascending
                select new
                {
                    Id = emp.Element("EmpId").Value,
                    Name = emp.Element("Name").Value,
                    Sex = emp.Element("Sex").Value,
                    WorkPhone = emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Home").Value,
                    HomePhone = emp.Elements("Phone").Single(phoneElement => phoneElement.Attribute("Type").Value == "Work").Value,
                };
Run Code Online (Sandbox Code Playgroud)

如果元素emp可能没有工作电话或家庭电话号码,则上述代码将引发异常Single.要处理这种情况,您必须将代码更改为:

(string)emp.Elements("Phone").SingleOrDefault(phoneElement => phoneElement.Attribute("Type").Value == "Home")
Run Code Online (Sandbox Code Playgroud)

SingleOrDefault将等于null如果没有"电话"元素满足条件和string上铸造XElement相当于XElement.Value.