Perhaps recursion with XML literals in VB.NET?

I have a class called Profile that has some simple properties, and then it can have a ProfileItem collection, which again has some simple properties, and then can have a ProfileItem (RECURSION) collection.

Now I'm trying to create a very simple save function using the XML literals that come with VB.NET (3.5).

The code I use is as follows:

Dim xdoc As XDocument = _ <?xml version="1.0" encoding="utf-8"?> <profiles> <%= _ From p In _Profiles _ Select <profile name=<%= p.Name %>> <%= _ From i In p.GetProfileItems _ Select <item> <name><%= i.Name %></name> <action><%= i.Action.ToString %></action> <type><%= i.Type.ToString %></type> <arguments><%= i.Arguments %></arguments> <dependencies> <%= _ From d In i.GetDependencies _ Select <dependency> <name><%= d.Name %></name> </dependency> _ %> </dependencies> </item> _ %> </profile> _ %> </profiles> 

The part associated with the tag should become recursive, but I donโ€™t know if it is somehow supported by this syntax.

Should I rewrite everything while avoiding using XML Literal to implement recursion?

+7
recursion
source share
1 answer

Recursion is one of the reasons I love VB.NET XML literals!

To perform recursion, you need a function that takes a ProfileItems collection and returns an XElement. You can then call this function recursively inside your XML literal.

In addition, for recursion to work, GetProfileItems and GetDependencies must have the same name (rename one of them) and display with the same Xml element structure. Here's what the recursive function looks like:

 Function GetProfileItemsElement(ByVal Items As List(Of ProfileItem) As XElement Return <items> <%= From i In Items _ Select <item> <name><%= i.Name %></name> <!-- other elements here --> <%= GetProfileItemsElement(i.GetDependencies) %> </item> %> </items> End Function 

The recursion will end when you go to an element that returns an empty list for the GetDependencies function. In this case, the nested items element will be empty: <items/> . XML literals are smart enough to combine the start and end tags of items when there are no children.

+9
source share

All Articles