C# Linq 2 XML不返回基于属性值中的元素

C# Linq 2 XML不返回基于属性值中的元素,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我有以下XML <?xml version="1.0" encoding="utf-8"?> <Employees> <Employee> <EmpId>1</EmpId> <Name>Sam</Name> <Sex>Male</Sex> <Phone Type="Home">423-555-0124</Phone> &l

我有以下XML

<?xml version="1.0" encoding="utf-8"?>
<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>
      <EmpId>5</EmpId>
      <Name>Kenneth Lowrey</Name>
      <Sex>Male</Sex>
      <Phone Type="Home">555-555-3477</Phone>
      <Phone Type="Work">444-123-2557</Phone>
      <Address>
        <Street>6026 Amberwoods Drive</Street>
        <City>Boca Raton</City>
        <State>FL</State>
        <Zip>33433</Zip>
        <Country>USA</Country>
      </Address>
    </Employee>
  </Employee>
</Employees>

1.
山姆
男性
423-555-0124
424-555-0545

我做错了什么

Element()
方法只返回与指定名称匹配的第一个元素。因此,对于每个
员工
,您只会收到第一部电话(家里)

更好的方法是使用
Elements()
方法获取与指定名称匹配的所有元素,然后按属性
Type
value进行筛选:

var empquery = from e in xEle.Descendants("Employee")
                select new
                {
                    name = e.Element("Name").Value,
                    homephone = (string)e.Elements("Phone").Where(x => x.Attribute("Type").Value == "Home").FirstOrDefault().Value,
                    workphone = (string)e.Elements("Phone").Where(x => x.Attribute("Type").Value == "Work").FirstOrDefault().Value
                };

e、 元素只获得第一个匹配项。使用Arturo建议的位置,或使用复数()获取所有“电话”标签。
var empquery = from e in xEle.Descendants("Employee")
                select new
                {
                    name = e.Element("Name").Value,
                    homephone = (string)e.Elements("Phone").Where(x => x.Attribute("Type").Value == "Home").FirstOrDefault().Value,
                    workphone = (string)e.Elements("Phone").Where(x => x.Attribute("Type").Value == "Work").FirstOrDefault().Value
                };