Reputation: 1795
I need to read and get all the customer ids from the xml. i tried the below code. but returns only one id. i have mentioned by xml file as well. Can anyone help on this issue.
var xdoc = XDocument.Load(@"d:\reply2.xml");
var entries = xdoc.Descendants("customerlist").Select(x => new { custid = (int) x.Element("customerid")});
foreach (var e in entries)
{
Console.WriteLine("Start: {0}", e.custid);
}
Console.ReadLine();
xml file.
<customerlist>
<customerid>1001</customerid>
<customerid>1002</customerid>
<customerid>1003</customerid>
<customerid>1004</customerid>
</customerlist>
Upvotes: 2
Views: 115
Reputation: 1
Here is the simple way to do this:
List <string> customerId = new List< string>();
string xmlString = @"Your XML string";
XDocument xDoc = XDocument.Parse(xmlString);
foreach (var element in xDoc.Descendants("customerid"))
{
customerId.Add(element.Value);
}
Upvotes: 0
Reputation: 236188
Your code is not working, because you are selecting all customerlist
from your file (there is only one such element, which is root), and then you are projecting each customerlist
element in result sequence to following anonymous type:
new { custid = (int)x.Element("customerid")}
What is happening here? You gen first customerid
element from x
(which is customerlist
) and return new anonymous object for each customerlist
item in source sequence. But you have only one customerlist
. So you have single anonymous object as query result.
If you want to select anonymous type with property custid
:
var entries = from c in xdoc.Root.Elements("customerid")
select new { custid = (int)c };
But I think you can simply select sequence of ids here without creating new type:
var ids = xdoc.Root.Elements("customerid").Select(c => (int)c);
Upvotes: 2