tags:

views:

123

answers:

4

Hello all.

I'm building a source code search engine, and I'm returning the results on a HTML page (aspx to be exact, but the view logic is in HTML).

When someone searches a string, I also return the whole line of code where this string can be found in a file. However, some lines of code come from HTML/aspx files and these lines contain HTML specific comments ().

When I try to print this line on the HTML page, it interprets it as a comment and does not show it on the screen....how should I go about solving this so that it actually shows up?

Any help would be welcomed. Thanks.

+6  A: 

As with any other HTML — covert special characters to entities. In particular < to &lt;

David Dorward
+3  A: 

Escape the characters < and > to &lt; and &gt;

see also: http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

Jasper
+2  A: 

Any time you output text into an HTML page, you must HTML-encode it. If you don't then not only will comments (and other markup-like strings) disappear, but you'll also have great big cross-site-scripting security holes, as potentially untrusted parties will be able to insert <script> into your security context.

(aspx to be exact

In .NET the HTML-encoding method is called, naturally enough, HTMLEncode. You might also use a web control that HTML-encodes automatically for you, for example a Literal with literalmode encode.

but the view logic is in HTML)

Not sure what you mean by that but if you're using innerHTML to set content from script, you'll need to write your own HTML-encoder, as there isn't one built in to JS:

// HTML-encode a string for use in text content or an attribute value delimited by
// double-quotes
//
function HTMLEncode(s) {
    return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

or, potentially better, use DOM methods and properties to set dynamic content rather than messing with HTML strings. (For setting text content, use element.textContent=, falling back to element.innerText for IE which doesn't support it.)

bobince
Thanks, great answer. I only need to use HttpUtility.HTMLEnconde for now. I'm not doing any computation on the client side, all is done on the server. So for now, I'm not going to use any javascript methods.
Andrei
A: 

You can use XML CDATA for this:

<![CDATA[ 
  some text with <!-- comments -->
]]>;
Андрей Костенко
In theory you could, but no browser supports it in text/html mode.
David Dorward
Also it's not secure for the general case even in `application/xhtml+xml` mode, since the text might include the `]]>` sequence.
bobince