I've tried searching on this but can't seem to find an answer anywhere, so hopefully someone here can help. I want to insert an conditional XML tag based on whether or not a count is above one, but am not sure how to do it.
For example, I have two XElements that are like this:
<Blob>
<Group>
Stuff 1
</Group>
</Blob>
and
<Blob>
<Group>
Stuff 1
</Group>
<Group>
Stuff 2
</Group>
</Blob>
I want this to end up being for the first one:
<BigGroup>
<Group/>
</BigGroup>
and for the second one:
<BigGroup>
<Groups>
<Group/>
<Group/>
</Groups>
</BigGroup>
Notice in the second one, their is a tag of wrapped around the two groups.
So, I want that condition in the XML Literal. What I've tried is:
Dim groups = If(<Blob>.<Group>.Count > 1, <Groups/>, Nothing)
Dim bigGroup = <BigGroup><%= groups %><%= from e in <Blob>.<Group> select e %><%= groups%></BigGroup>
But that is not working. Does anyone have a way to do this from within the XML Literal as desired above?
You can just place the If statement inside the XML Literal. Also, it's smart enough to output an IEnumerable(Of XElement)
by simply referencing the variable inside <%= %>
.
Here's the code.
Sub Main()
Dim SingleGroup = <Blob>
<Group>Stuff 1</Group>
</Blob>
Dim TwoGroups = <Blob>
<Group>Stuff 1</Group>
<Group>Stuff 2</Group>
</Blob>
Dim BigGroup1 = BigGroup(SingleGroup.<Group>)
Dim BigGroup2 = BigGroup(TwoGroups.<Group>)
Console.WriteLine(BigGroup1)
Console.WriteLine()
Console.WriteLine(BigGroup2)
Console.ReadLine()
End Sub
Function BigGroup(ByVal groups As IEnumerable(Of XElement)) As XElement
Dim result = <BigGroup>
<%= If(groups.Count > 1, _
<Groups><%= groups %></Groups>, _
groups.SingleOrDefault) %>
</BigGroup>
Return result
End Function
The output is:
<BigGroup>
<Group>Stuff 1</Group>
<BigGroup>
<BigGroup>
<Groups>
<Group>Stuff 1</Group>
<Group>Stuff 2</Group>
</Groups>
</BigGroup>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With