Question Using Control Structures in XML Literals???

wyldbill_cane

New member
Joined
May 4, 2009
Messages
2
Location
Houston
Programming Experience
10+
have been recently doing a bunch of work using XML Literals.

The syntax is very reminiscent of .jsp code and subsequent implementations in a variety of other frameworks/languages.

My problem is that I want to include control structures in the embedded XML. Specifically, I want to include or exclude an entire element (not just its contents) based on a boolean expression. The question extends to other control structures as well though.

I'd expect the <% %> syntax to support inling of code but that doesn't seem to function in VB.net's implementation (as opposed to the <%= %> for inlining the result of an evaluated expression, which does).

Here's some very simple code by way of example only.

VB.NET:
Public Class Foo
    Private bar As String = Nothing
    Private baz As String = Nothing
    Private printBar As Boolean = False
    Private printBaz As Boolean = False

    Public Function getXML() As XElement
        Dim ret As XElement = <foo></foo>
        If printBar Then ret.Add(<bar><%= bar %></bar>)
        If printBaz Then ret.Add(<baz><%= baz %></baz>)
        Return ret
    End Function

    Public Function getXMLBad() As XElement
        Dim ret As XElement = <foo>
                                  <% If printBar Then %>
                                      <bar><%= bar %></bar>
                                  <% End If %>
                                  <% If printBaz Then %>
                                      <baz><%= baz %></baz>
                                  <% End If %>
                              </foo>
        Return ret
    End Function

End Class

I'd much prefer to use the format of getXMLBad() if possible. In this short example it doesn't seem critical, but in much larger examples, the inlining of the logic is more readable and maintainable than the "assembly" style in getXML(). This especially true when the logic is in the middle of large block of static XML and when coding to a very strict or complex schemas.

I'd be interested in the capability to extend this to Looping constructs as well.

Any comments, links or pointers would be appreciated.

TIA,
-bill
 
One way to accomplish this is to do do something like

<%= If(flag, <a_info><%= getAResponse() %></a_info>, <b_info><%= getBResponse() %></b_info>) %>

but I'm looking for something a bit less ugly.

-bill
 
Back
Top