Click here to Skip to main content
13,300,002 members (58,716 online)
Click here to Skip to main content
Add your own
alternative version

Stats

24.9K views
8 bookmarked
Posted 16 Nov 2012

Read XML with Descendants Method (XName)

, 19 Nov 2012
Rate this:
Please Sign up or sign in to vote.
Understanding Descendants and avoiding misconception with this method

This post is about understanding Descendants and avoiding misconception with this method.
Recently, I read one question on StackOverFlow about reading XML using LINQ To XML to get node values. In that, a developer made use of Descendants Method to get the child node values.

Let's see the actual problem here. Following is the XML to read and the developer wrote code to read out the value of orderid node.

<ordersreport date="2012-08-01">
<returns>
      <amount>
        <orderid>2</orderid>
        <orderid>3</orderid>
        <orderid>21</orderid>
        <orderid>23</orderid>
      </amount>
    </returns>
</ordersreport>

So code is written like this:

var amount = documentRoot.Descendants("Amount")
           .Select(y => new
           {
              OrderId = (int)y.Element("OrderId")
           });
           foreach (var r in amount)
           {
              Console.WriteLine(r.OrderId);
           }

Output of the above code is: 2.

That is only first orderid element value which is the child of Amount. So, the misconception here by developer of the code is Descendants("Amount") returns child element of the Amount tag, i.e., all orderId element.

Now to Understand Descendants function in a better way, I visited the MSDN link which says something like this
XContainer.Descendants Method (XName) - Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching XName are included in the collection. So as per the definition on MSDN problem with code...

var amount = doc.Descendants("Amount")
  .Select(y => new
  {
   OrderId = (int)y.Element("OrderId")
   });

...will give you Element Amount and when you write y.Element("OrderId") will return you fist element of its child.

Descendants - doesn't mean than it returns the child element of element name rather than method. Look for descendants of element or if name of element specified as parameter than matching descendants.
Finally, I got the following solution to get it to work properly.

XElement documentRoot  = 
     XElement.Parse (@"<ordersreport date="2012-08-01">
                             <returns>
                              <amount>
                                  <orderid>2</orderid>             
                                  <orderid>3</orderid>
                                  <orderid>21</orderid>
                                  <orderid>23</orderid>
                               </amount>
                             </returns>
                        </ordersreport>");

Solution 1

var orderids = from order in
                  documentRoot.Descendants("Amount").Descendants()
                  select new
                  {
                     OrderId = order.Value
                  };

As per the information on MSDN, documentRoot.Descendants("Amount").Descendants() gives a list of orderId elements.

Solution 2

var orderids = from order in
                    documentRoot.Descendants("OrderId")
                    select new
                    {
                       OrderId = order.Value
                    };

Or the second solution is just a bit easy than this. Just make use of documentRoot.Descendants("OrderId") that will give all orderid element.

Conclusion

This post is just for avoiding the misconception related to Descendants and understanding it properly.

Leave your comments if you like it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a ITA in MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



You may also be interested in...

Pro

Comments and Discussions

 
GeneralGreat Artile Pin
Member 1059723431-Mar-15 10:48
memberMember 1059723431-Mar-15 10:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 19 Nov 2012
Article Copyright 2012 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid