tags:

views:

570

answers:

2

I have an XML File that I am processing using LINQ. I want to basically serialize the XML data into custom objects but don't know how.

Simplified XML

<Data>
   <Group id="1">
      <Child id="1"/>
      <Child id="2"/>
      <Child id="3"/>
   </Group>
   <Group id="2">
      <Child id="1"/>
      <Child id="2"/>
      <Child id="3"/>
   </Group>
</Data>

I have a class called Group with a property called Children that is a list of (Child).

I can do the following in linq to generate the Enurable( of Group):

 dim g = From item In _
 XElement.Load("XMLFile.xml", LoadOptions.None)...<Group> _
 Select New nABLE4ConfigInfo.Group(item.@id)

How can I finish the above LINQ query to populate the Children property of the Group object?

+2  A: 

I think this class, paired with System.Xml.Serialization.XmlSerializer, will do the trick:

<Serializable> _
Public Class Data

   <Serializable> _
   Public Class Group

       <Serializable> _
       Public Class Child
           <XmlAttribute> _
           Public id As Integer
       End Class


       <XmlArray> _
       Public Child() As Child

       <XmlAttribute> _
       Public id As Integer

   End Class

  <XmlArray> _
  Public Group() As Group
End Class

The class may need some work yet: getting the arrays right can be tricky.

Joel Coehoorn
I was afraid of this answer. The XML I presented is greatly simplified. I use XML serialization throughout this application but can not for this.
jercra
Well this isn't the only way: there are at least 1/2 dozen different ways to handle xml in .Net. You're using an XDocument and I showed you serialization, but there's also XmlDocument or DataSet.ReadXml(), to name a couple. You could read by hand, if you have to.
Joel Coehoorn
I understand. Sorry if I wasn't clear. I already have a method that handles this using the XML DOM and works just fine. I just wanted a solution using LINQ since it's much cleaner.
jercra
+1  A: 

It's as simple as nested select statements and the right constructor on the class.

 Dim g = From item In _
      XElement.Load("XMLFile.xml", LoadOptions.None)...<Group> _
             Select New Group(id:=item.@id, _
                   Children:=(From c In item...<Child>  Select c.@id).ToList)
jercra