views:

371

answers:

4

I'm having a problem using XML literals with a StringBuilder in VB 2008. If I use this code everything is fine.

Dim html As New System.Text.StringBuilder

html.Append(<html><body></body></html>)

MsgBox("hello")

Now the problem is I want to wrap HTML around something that is generated in code.

html.Append(<html><body>)

msgbox("nothing happens")

When the HTML doesn't have the corresponding ending tag, it acts like it goes beyond the ) and keeps looking for it.

Is there something I am doing wrong here?

+1  A: 

The obvious hunch would be that XML literals require well formed XML. If you want to wrap things, drop in an embedded expression as in...

html.Append(<html><body><%= contentExp %></body></html>)
Larsenal
+2  A: 

I've never used VB's XML literals but I have built up a lot of XML. I like to use the StringWriter/XMLTextWriter classes:

StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
    XmlTextWriter xw = new XmlTextWriter(sw);
    xw.WriteStartElement("html");
    xw.WriteStartElement("body");
    xw.WriteRaw(contentExp);
    ...
    wr.WriteEndElement();   // body
    wr.WriteEndElement();   // html
}
// do something with sb.ToString()?
n8wrl
+1  A: 

Because you're not forming a proper XML in your XML Literal statement (in your case you're not closing your tags), you can't use XML Literals here. You either need to have your XML literals be proper XML, or alternatively convert your code to use them as strings. Thus:

html.Append("<html><body>")

msgbox("nothing happens")
John Christensen
+1  A: 

Not an answer, but question back to you. What would be the value of using XML Literals with string builder. It seems at least to me that that goes against the grain. Create your XML using literals and then just get its string representation using the .ToString() method call if you need a string.