C# 中的 Linq 到 xml
场景:
- 网格视图填充到 WPF 窗口中。
- 在代码后面有一个静态列表。(我想从 xml 文件中获取)。
尝试将静态列表移动到 xml 文件中。为此,我以以下格式创建了一个 ml 文件
<customers>
<customer Name="abc"/>
<customer Name="def"/>
</customers>
CodeBehind:
Xdocument doc=Xdocument.load("customers.xml");
var customerList = (from e in doc.Descendants("Cusomters")
select new
{
CustomerName = e.Attribute("Name").Value
}).ToList();
我无法将客户名称从 xml 文件移动到 customerList。如果有人可以帮助我移动,我将不胜感激向前。
Scenario:
- Grid view gets populated in WPF window.
- Having a static list in code behind.(which i want to get from a xml file).
Trying to move the static list into an xml file.For that i created a ml file in the following format
<customers>
<customer Name="abc"/>
<customer Name="def"/>
</customers>
CodeBehind:
Xdocument doc=Xdocument.load("customers.xml");
var customerList = (from e in doc.Descendants("Cusomters")
select new
{
CustomerName = e.Attribute("Name").Value
}).ToList();
I am unable to get the customer names from the xml file to the customerList.I would appreciate if someone can help me to move forward.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
“Customers”
拼写错误,应为“Customers”
。显然这不是您正在使用的代码,因为它甚至无法编译。应该是这样的:
你真的应该提到它无法编译的事实。那,或者您错误地手工复制了它,这也无助于我们为您提供帮助。
这里的逻辑问题是您要求所有
Customers
标签,请注意末尾的s
。您确实想要查找具有name
属性的Customer
标记。Customer*s*
只是顶级组。"Cusomters"
is spelled incorrectly, should be"Customers"
.Obviously this is not the code your are using since it doesn't even compile. It should be this:
You really should mention the fact that it won't compile. That, or you copied it in by hand incorrectly, which doesn't help us help you either.
The logical problem here is that you are asking for all
Customers
tags, note thes
at the end. You really want to look forCustomer
tags, which have aname
attribute.Customer*s*
is simply the top level group.使用
customer
而不是Cusomters
(XML 区分大小写):Use
customer
instead ofCusomters
(XML is case-sensitive):您很可能需要一个
List
,这样您就不需要投影到匿名类 - 您的查询中也存在拼写错误(“Cusomters”
):或使用扩展方法语法:
You most likely want a
List<string>
so you don't need to project to an anonymous class - also there is a typo in your query ("Cusomters"
):or with extension method syntax:
我总是使用 :
来表示这样的小片段。
Ive always used :
for small snippets like this.