xmlvb.netxml-literals

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.


Solution

  • If I understand correctly what you are trying to do, you can use the StringBuilder. Use the StringBuilder.Append method and append the XmlElement 'OuterXml' property.

    For example:

    sb.Append(xmlElement.OuterXml)