Html

Html is a library for generating html through code. Here are some examples of what it does.

Simple Html With Content

Console.WriteLine(new Element("b").Update("Chris"));
produces:

<b>Chris</b>

Attributes Should Be Easy

Easily add attributes without worrying about double quotes, single quotes, no quotes, just enter the attributes and Html will take care of the rest:

Console.WriteLine(new Element("input", "type=text;id=firstname;"));
produces:

<input type="text" id="firstname"></input>

Output to Anything

Output to any TextWriter:

new Element("i")
  .Update("Wow")
  .Render(Console.Out);
Produces this in the console output window:

<i>Wow</i>
Output to any Stream

string expected = "<p>Hello World</p>";
byte[] buffer = new byte[expected.Length];
using (MemoryStream stream = new MemoryStream(buffer)){
  Element para = new Element("p").Update("Hello World");
  para.Render(stream);
  string actual = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
  Assert.AreEqual(expected, actual);
}
Want to control formatting? Use an XmlTextWriter:

Element select = new Element("select");
for(int i=0;i<5;i++){
  select.Append(
    new Element("option")
      .AddAttribute("value", i)
      .Update("Item {0}", i));
}
using (StringWriter text = new StringWriter()){
  XmlTextWriter xml = new XmlTextWriter(text);
  xml.Formatting = Formatting.Indented;
  select.Render(xml);
  Console.WriteLine(text.ToString());
}  

Styles and CSS Classes

Add styles and css classes easily with Html's fluent interfaces:

new Element("p")
  .AddCssClasses("blog")
  .AddStyle("padding:10px;line-height:150%;")
  .Render(Console.Out);
produces:

<p style="padding:10px;line-height:150%;" class="blog"></p>

Everything is a String

Elements are implicitly converted to strings. Therefore any method that needs to return a string, can return an Element; and any method that accepts a string can accept an element.

Given this method:

public string CreateSelect(){
  Element select = new Element("select");
  for(int i=0;i<5;i++){
    select.Append(
      new Element("option")
        .AddAttribute("value", i)
        .Update("Item {0}", i));
  }
  return select;
}
The following line:

Console.WriteLine(CreateSelect());
produces:

<select><option value="0">Item 0</option><option value="1">Item 1</option><option value="2">Item 2</option><option value="3">Item 3</option><option value="4">Item 4</option></select>
Concatenate strings and Elements

Console.WriteLine("<b>Hello</b> "+new Element("i").Update("World"));
produces:

<b>Hello</b> <i>World</i>

Last edited Jul 31, 2008 at 2:34 AM by chrcar01, version 15