2009-03-03 94 views
15

我想將Silverlight DataGrid綁定到WCF服務調用的結果。我沒有看到網格中顯示的數據,所以當我運行調試器時,我注意到XDocument.Descendants()即使在傳入有效元素名稱時也沒有返回任何元素。這裏是從服務傳回的XML:XDocument.Descendants()沒有返回任何元素

<ArrayOfEmployee xmlns="http://schemas.datacontract.org/2004/07/Employees.Entities" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
    <Employee> 
    <BirthDate>1953-09-02T00:00:00</BirthDate> 
    <EmployeeNumber>10001</EmployeeNumber> 
    <FirstName>Georgi</FirstName> 
    <Gender>M</Gender> 
    <HireDate>1986-06-26T00:00:00</HireDate> 
    <LastName>Facello</LastName> 
    </Employee> 
    <Employee> 
    <BirthDate>1964-06-02T00:00:00</BirthDate> 
    <EmployeeNumber>10002</EmployeeNumber> 
    <FirstName>Bezalel</FirstName> 
    <Gender>F</Gender> 
    <HireDate>1985-11-21T00:00:00</HireDate> 
    <LastName>Simmel</LastName> 
    </Employee> 
</ArrayOfEmployee> 

,這裏是我使用的結果加載到匿名對象的集合,使用LINQ to XML,然後收集綁定到網格的方法。

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs args) 
{ 
    if (args.Error != null) return; 
    var xml = XDocument.Parse(args.Result); 
    var employees = from e in xml.Descendants("Employee") 
        select new 
        { 
         EmployeeNumber = e.Element("EmployeeNumber").Value, 
         FirstName = e.Element("FirstName").Value, 
         LastName = e.Element("LastName").Value, 
         Birthday = e.Element("BirthDate").Value 
        }; 
    DataGrid.SelectedIndex = -1; 
    DataGrid.ItemsSource = employees; 
} 

任何想法爲什麼xml.Descendants("Employee")不返回任何東西?

謝謝!

回答

33

傳遞給Descendents的字符串參數實際上被隱式轉換爲XName對象。 XName表示完全限定的元素名稱。

該文件定義了一個命名空間「i」,因此我相信您需要使用完全限定的名稱來訪問Employee。即。我:員工,其中前綴「我:其實解析爲完整的命名空間字符串

你有沒有嘗試過這樣的:

XName qualifiedName = XName.Get("Employee", "http://www.w3.org/2001/XMLSchema-instance"); 

var employees = from e in xml.Descendants(qualifiedName) 

... 
+1

你說得對,我需要包含命名空間。感謝您的幫助! – 2009-03-03 01:35:56

0

您還沒有包括從父元素的命名空間:

XNameSpace ns = "http://schemas.datacontract.org/2004/07/Employees.Entities"; 
foreach (XElement element in xdoc.Descendants(ns + "Employee") 
{ 
    ... 
}