Reputation: 404
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?
Upvotes: 0
Views: 1260
Reputation: 404
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)
Upvotes: 1
Reputation: 415630
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.
Upvotes: 2