【问题标题】:XDocument.Descendants() not returning any elementsXDocument.Descendants() 不返回任何元素
【发布时间】:2010-10-10 22:04:36
【问题描述】:

我正在尝试将 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 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") 不返回任何内容吗?

谢谢!

【问题讨论】:

    标签: silverlight wcf-binding linq-to-xml


    【解决方案1】:

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

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

    您是否尝试过类似的方法:

    XName qualifiedName = XName.Get("Employee", "http://www.w3.org/2001/XMLSchema-instance");
    
    var employees = from e in xml.Descendants(qualifiedName)
    
    ...
    

    【讨论】:

    • 你说得对,我需要包含命名空间。感谢您的帮助!
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 2020-04-29
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      相关资源
      最近更新 更多