2

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>
Innovative Thinker
  • 1,735
  • 2
  • 14
  • 24
  • possible duplicate of [How does one parse XML files?](http://stackoverflow.com/questions/55828/how-does-one-parse-xml-files) – DarkWanderer Mar 27 '14 at 11:25

2 Answers2

2

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);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

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);
}
Daniel
  • 471
  • 5
  • 28