Solved

Retrieve complex data in Linq to XML

Posted on 2011-09-13
5
329 Views
Last Modified: 2012-05-12
I have an XML data source having the following layout:
<Items>
<Item Name="Bob" Color="Green" />
<Item Name="Carol" Color="Red">
  <Pet Type="Cat" Age="3" />
  <Pet Type="Dog" Age="7" />
</Item>
<Item Name="Ted" Color="Blue" />
</Items>

Open in new window


I want to use Linq to XML to get this data into an Items structure defined as follows:
public class Item
{
  public string Name {get; set;}
  public string Color {get; set;}
  public List<Pet> Pets {get; set;}
}

Open in new window


public class Pet
{
  public string Type {get; set;}
  public int Age {get; set;}
}

Open in new window


I'm trying to do something like this:
List<Item> myItems = from e in XElement.Load("MyData.xml").Elements("Item")
  select new Item
  {
    Name = (string)e.Attribute("Name"),
    Color = (string)e.Attribute("Color"),
    Pets = (List<Pet>)e.Descendants()
  }

Open in new window


The above Linq statement is wrong, but should give a good idea of what I'm trying to achieve. I can get Name and Color, but can't figure out how to get the list of Pets.

Thanks for helping!


0
Comment
Question by:wlevy
5 Comments
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36528802
Hi!
Try
List<Item> myItems = from e in XElement.Load("MyData.xml").Elements("Item")
  select new Item
  {
    Name = (string)e.Attribute("Name"),
    Color = (string)e.Attribute("Color"),
    Pets = e.Descendants().ToList<Pet>()
  }
0
 
LVL 16

Expert Comment

by:Easwaran Paramasivam
ID: 36528899
Validate your xml is correctly formatted.

XDocument xmlDoc = XDocument.LoadXML("your xml in string format"); //Load method to load a xml file
var q = from c in xmlDoc.Descendants("Item")
            select new Item()
{
 Name = c.Attribute("Name").Value;
Color = c.Attribute("Color").Value;
Pets = from v in c.XMLElement("Pets")
         select new Pet()
         {
          Type = v.Attribute("Type").Value;
          Age = v.Attribute("Age").Value;

         }

}

http://blogs.msdn.com/b/wriju/archive/2008/02/18/linq-to-xml-creating-complex-xml-through-linq.aspx
http://www.joe-stevens.com/2010/01/08/linq-to-xml-tutorial/
http://www.techrepublic.com/blog/programming-and-development/access-xml-data-using-linq-to-xml/594
http://www.google.co.in/#sclient=psy&hl=en&source=hp&q=Linq+to+xml+complex&pbx=1&oq=Linq+to+xml+complex&aq=f&aqi=g2g-v2g-b1&aql=&gs_sm=e&gs_upl=446775l448585l2l449411l8l7l0l0l0l0l592l1591l4-1.2l3l0&bav=on.2,or.r_gc.r_pw.&fp=1bc11de366406738&biw=1280&bih=847
0
 

Author Comment

by:wlevy
ID: 36531452
Neither of the above solutions will work. Did you test them?
0
 
LVL 4

Accepted Solution

by:
guramrit earned 500 total points
ID: 36535232
It'll work, check this...
 
XDocument xmlDoc = XDocument.Load("resources\\data.xml"); //Load method to load a xml file
            var q = (from c in xmlDoc.Descendants("Item")
                     select new Item()
                                {
                                    Name = c.Attribute("Name").Value,
                                    Color = c.Attribute("Color").Value,
                                    Pets = (from v in c.Elements("Pet")
                                            select new Pet()
                                                       {
                                                           Type = v.Attribute("Type").Value,
                                                           Age = Convert.ToInt32(v.Attribute("Age").Value)
                                                       }).ToList()

                                }).ToArray();

Open in new window


Change "resources\\data.xml" to your file path.
0
 

Author Closing Comment

by:wlevy
ID: 36536166
Perfect! Exactly what I needed. Thank you.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This is a video describing the growing solar energy use in Utah. This is a topic that greatly interests me and so I decided to produce a video about it.
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now