Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Retrieve complex data in Linq to XML

Posted on 2011-09-13
5
332 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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

792 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