Tutorial :Generate Complex Object from LINQ to XML in VB .NET



Question:

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?


Solution:1

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.


Solution:2

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)  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »