Solved

Retrieve complex data in Linq to XML

Posted on 2011-09-13
5
328 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
Comment Utility
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
Comment Utility
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
Comment Utility
Neither of the above solutions will work. Did you test them?
0
 
LVL 4

Accepted Solution

by:
guramrit earned 500 total points
Comment Utility
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
Comment Utility
Perfect! Exactly what I needed. Thank you.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
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…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

743 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

17 Experts available now in Live!

Get 1:1 Help Now