tags:

views:

1339

answers:

3

Consider the following code in VB9:

Dim text = "Line1<br/>Line2"
Dim markup = <span><%= text %></span>.ToString

While I was hoping markup would end up being <span>Line1<br/>Line2</span>, it actually evaluates to <span>Line1&lt;br/&gt;Line2</span>.

Is there any way to get the value of the variable not to be HTML encoded?

P.S.: This is an oversimplified example of what I'm trying to do. I know this could be rewritten a number of ways to make it work, but the way my code is constructed, un-encoding the variable would be optimal. If that's not possible, then I'll go down a different road.

More detail: The "text" is coming from a database, where a user can enter free-form text, with carriage returns. The output is HTML, so somehow I need to get the value from the database and convert the carriage returns to line breaks.

+2  A: 

This behavior is "By Design." When embedding a string expression inside an XML literal the value will be escaped to be a legal string value.

To get the behavior you are looking for you'll need to be embedding an XElement/XNode within an XML literal. Take the following example. It will correctly keep the \ tag as an XElement.

Dim text2 = <a>Line<br/>Line</a>
Dim markup2 = <span><%= text2 %></span>.ToString

One way to achieve this is to fake an XElement. To make the text a valid string, simply wrap it on both ends with a normal tag, <a> for example. This is now a parsable XML fragment. Once you have an XElement, it's easy to get the embedded behavior you are looking for

Dim text = "Line1<br/>Line2"
Dim text2 = XElement.Parse("<a>" + text + "</a>")
Dim markup = <span><%= text2.Nodes %></span>.ToString
JaredPar
See detail above (just added). I don't have the luxury of separating the text into elements unless I parse the incoming text and build each element, which I'm trying to avoid.
gfrizzle
Check out the additional comment i made. You will have to parse complete inputs but not each individual one.
JaredPar
A: 

In VB.NET, you can directly write XML literals

Dim markup As XElement = <span>Line1<br/>Line2</span>
  • The VB compiler “sees” the XML,
  • and creates the equivalent XLinq commands for you.

Read more about XML Literals in VB.NET.

Jenko
That is correct, but it doesn't address the problem. I have text (from the db) with carriage returns. I can replace the CR's with "<br/>", but the XML literal doesn't recognize them when I use it in <%# text %>. @JaredPar's XElement.Parse got me around this issue.
gfrizzle
Oh sorry, yeah, I didn't notice that you already knew about XML literals!
Jenko
A: 

Can the above VB.Net code which produces easy html/xml be done in C#

e.g.

Dim markup = < span><%= text2.Nodes %>< /span>.ToString

Possibly something like

var markup = < span><%= text2.Nodes %>< /span>.ToString();

I can't seem to get this to work in C#