Reputation: 1034
Scenario:
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.
Upvotes: 0
Views: 224
Reputation: 5829
Ive always used :
doc.root.elements("Customer")
for small snippets like this.
Upvotes: 0
Reputation: 124642
"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:
XDocument doc = XDocument.Load( "customers.xml" );
var customerList = (from e in doc.Descendants( "customer" )
select new
{
CustomerName = e.Attribute( "Name" ).Value
}).ToList();
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 the s
at the end. You really want to look for Customer
tags, which have a name
attribute. Customer*s*
is simply the top level group.
Upvotes: 3
Reputation: 160892
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"
):
var customerList = (from e in doc.Descendants("Customer")
select e.Attribute("Name").Value).ToList();
or with extension method syntax:
var customerList = doc.Descendants("Customer")
.Select( e => e.Attribute("Name").Value)
.ToList();
Upvotes: 2
Reputation: 56162
Use customer
instead of Cusomters
(XML is case-sensitive):
from e in doc.Descendants("customer")
Upvotes: 2