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>
1

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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);
}

2 Comments

but i have file not xml string
You can load XML file instead of parse like XDocument doc = XDocument.Load("xmlfile.xml");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.