2016-03-02 75 views
2

我有以下XML ...LINQ的2 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> 

我有以下的控制檯應用程序代碼...

using System; 
using System.Xml.Linq; 
using System.Linq; 

class Program 
{ 
    public static void Main(String[] args) 
    { 
     String strPath = @"C:\XMLExample\Employees.xml"; 
     XElement xEle = XElement.Load(strPath); 

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

     foreach (var e in empquery) 
     { 
      Console.WriteLine("{0}'s home phone is {1} work phone is {2}", e.name, e.homephone, e.workphone); 
     } 

     Console.WriteLine("Press <enter> to continue"); 
     Console.ReadLine(); 
    } 
} 

我想在我的查詢表達式中分隔家庭和工作電話號碼。

但是我只抽到了家裏的電話號碼..

enter image description here

我在做什麼錯?

+0

e.Element只得到第一個匹配。使用Arturo建議或使用複數Elements()來獲得所有'手機'標籤的地方。 – jdweng

回答

2

Element()方法只返回與指定名稱匹配的第一個元素。因此,對於每個Employee,您只會獲得第一個電話(主頁)。

更好的方法是使用Elements()方法來得到符合指定名稱的所有元素,然後通過屬性Type值濾波器:

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 
       };