Search code examples
xmlvb.netliteralsxelement

Can I escape XML characters like brackets that are contained within XML literal syntax of VB.NET?


A while back, I asked this question:

Does VB.NET have a multi-line string declaration syntax equivalent to c#?

Here I was introduced to XML literals in VB.NET. Using this syntax, I was able to simulate the multi-line string syntax available in c# using the @ symbol. However, I've come upon a snag. It seems that putting < or > in the text does not sit well in the belly of Visual Studio. Take this code as an example:

Dim Sql As String = <a><![CDATA[]]>
                        <text instead pointy brackets fails>
                    </a>.Value

Can I somehow escape these brackets or tell the literal not to care about it?


Solution

  • You need to put the text within the CDATA section:

    Dim Sql As String = <a><![CDATA[
    <text instead pointy brackets fails>
    ]]></a>.Value
    
    Console.WriteLine("===")
    Console.WriteLine(Sql)
    Console.WriteLine("===")
    

    should output:

    ===
    
    <text instead pointy brackets fails>
    
    ===
    

    Note that CDATA will also preserve leading spaces in your text; that is why I removed them from the bracketed text.