我正在尝试将Silverlight DataGrid绑定到WCF服务调用的结果。我没有看到网格中显示的数据,所以当我浏览调试器时,我注意到XDocument.Descendants()即使在传入有效的元素名称时也没有返回任何元素。以下是从服务传回的XML:

<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到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(&quot; Employee&quot;)没有返回任何内容?

谢谢!

有帮助吗?

解决方案

传递给后代的字符串参数实际上是隐式转换为XName对象。 XName表示完全限定的元素名称。

该文档定义了名称空间“i”,因此我认为您需要使用完全限定名称来访问Employee。即。 i:Employee,前缀“i:实际上解析为完整的命名空间字符串。

你有没有试过像:

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

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

...

其他提示

您没有包含父元素的命名空间:

XNameSpace ns = "http://schemas.datacontract.org/2004/07/Employees.Entities";
foreach (XElement element in xdoc.Descendants(ns + "Employee")
{
    ...
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top