Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strings in XML Literals

I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.

I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument

I have 2 questions, the second regarding a workaround due to my inability to figure out the first.

1: Ideal solution

I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death

Dim xConnections As XElement        
For Each connection As Connection In connections.AsList
    For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
        xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>>  </Connections>
    Next
Next

I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.

2: Cludgy workaround

Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.

I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.

like image 217
johnc Avatar asked Sep 23 '26 13:09

johnc


1 Answers

VB.NET XML Literals are very powerful, but most often adding some LINQ to them makes them truly awesome. This code should do exactly what you're trying to do.

Dim Elements = New Dictionary(Of String, String)
Elements.Add("Key1", "Value1")
Elements.Add("Key2", "Value2")
Elements.Add("Key3", "Value3")

Dim xConnections = <Connections>
                       <%= From elem In Elements _
                           Select <<%= elem.Key %>><%= elem.Value %></> %>
                   </Connections>

The empty closing tag </> is all that is needed for the vb compiler to properly construct an xml element whose name is generated from a value within a <%= %> block.

Calling xConnections.ToString renders the following:

<Connections>
    <Key1>Value1</Key1>
    <Key2>Value2</Key2>
    <Key3>Value3</Key3>
</Connections>
like image 168
CoderDennis Avatar answered Sep 25 '26 09:09

CoderDennis