XDocument.Descendants()不返回任何元素 [英] XDocument.Descendants() not returning any elements
问题描述
我正在尝试将Silverlight DataGrid绑定到WCF服务调用的结果.我没有看到网格中显示的数据,因此当我通过调试器运行时,我注意到XDocument.Descendants()不会返回任何元素,即使我传入了有效的元素名称也是如此.这是从服务传回的XML:
I'm trying to bind a Silverlight DataGrid to the results of a WCF service call. I was not seeing the data displayed in the grid, so when I ran through the debugger, I notice that XDocument.Descendants() was not returning any elements even when I was passing in a valid element name. Here is the XML that is passed back from the service:
<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,然后将集合绑定到网格.
And here is the method I use to load the results into a collection of anonymous objects, using Linq to XMl, and then bind the collection to the grid.
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")
不返回任何内容吗?
Any idea why xml.Descendants("Employee")
doesn't return anything?
谢谢!
推荐答案
传递给Descendents的字符串参数实际上隐式转换为XName对象. XName代表完全限定的元素名称.
The string parameter passed to Descendents is actually implicitly converted to an XName object. An XName represents a fully qualified element name.
该文档定义了一个命名空间"i",因此我认为您需要使用完全限定的名称来访问Employee. IE. i:Employee,其中前缀"i:"实际上解析为完整的名称空间字符串.
The document defines a namespace "i", therefore I believe you need to use the fully qualified name to access Employee. ie. i:Employee, where the prefix "i: actually resolves to the full namespace string.
您是否尝试过类似的操作:
Have you tried something like:
XName qualifiedName = XName.Get("Employee", "http://www.w3.org/2001/XMLSchema-instance");
var employees = from e in xml.Descendants(qualifiedName)
...
这篇关于XDocument.Descendants()不返回任何元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!