views:

44

answers:

4

Hi there,

I have an ASP.NET web forms site with a rather large menu. The HTML for the menu is dynamically generated via a method in the C# as a string. I.e., what is being returned is something like this:

<ul><li><a href='default.aspx?param=1&anotherparam=2'>LINK</a></li></ul>

Except it is a lot bigger, and the lists are nested up to 4 deep.

This is written to the page via a code block.

However, instead of returning a flat string from the method I would like to return it as formatted HTML, so when rendered it looks like this:

<ul>
    <li>
        <a href='default.aspx?param=1&anotherparam=2'>LINK</a>
    </li>
</ul>

I thought about loading the html into an XmlDocument but it doesn't like the & character found in the query strings.

Anyone have any ideas?

A: 

Try loading the HTML into the HTML Agilty Pack. It is an HTML parser that can deal with HTML fragments (and will be fine with & in URLs).

I am not sure if it can output pretty printed (what you call "formatted") HTML, but that would be my first approach.

Oded
+3  A: 

Maybe you can work with an HtmlTextWriter? It has Indenting capabilities and it may actually be a cleaner thing as you could write straight into the output stream, which should be more "in the flow" than generating a string in memory etc.

flq
+1  A: 

Is there a reason you want to do this? This implicitly minified HTML will perform slightly better anyway. If you do still need to render the HTML for pretty display, you will either need to incorporate indentation into the logic that generates the output HTML or build your content using ASP.NET controls and then call Render().

Phil Hunt
or else use `HtmlTextWriter` like flq described.
Phil Hunt
its mainly so it is readable during development, its likely the minified HTML will be used in the live environment
Scozzard
A: 

I like to use format strings for this sort of thing, your HTML output would be generated with;

String.Format("<ul>{0}\t<li>{0}\t\t<a href='{2}'>{3}</a>{0}\t</li>{0}</ul>",
               System.Environment.NewLine,
               myHrefVariable,
               myLinkText);
Dave Anderson