title: How to build HTML from Code in C#
body: <p>I need to create an HtmlHelper in my MVC application which renders out some nested and fairly complex UL/LI (tree-like) structures. The <code>HtmlTextWriter</code> and <code>XmlTestWriter</code> classes provide means to construct proper HTML, but they are forward-only thus making my job pretty difficult, since after you rendered a tag you don't have a reference to "parent" tag.</p>
  
  <p><code>XDocument</code> and <code>XElement</code> classes were the next candidates I looked at, but they have been created for XML and not for HTML, which might result in <em>no-so-valid</em> HTML (self-closing tags etc.).</p>
  
  <p>How would I go about this?</p>
  
  <p><a href="https://stackoverflow.com/questions/2432551">This alleged duplicate</a> is not really a duplicate and doesn't answer my question at all. It is about building an HTML-Helper rendering a single Html-Tag. This is not what I am after. I'd like to know how to build an entire DOM in C# code.</p>