Skip to content

Instantly share code, notes, and snippets.

@nicosantangelo
Created September 3, 2012 14:23
Show Gist options
  • Save nicosantangelo/3609677 to your computer and use it in GitHub Desktop.
Save nicosantangelo/3609677 to your computer and use it in GitHub Desktop.
Extension class for XmlTextWriter so it doesn't close empty tags and leaves a new line between them. This won't produce A well indented HTML, but the new line will prevent a bad render. Credits: http://goo.gl/Kmi76
public class CustomHtmlWriter: XmlTextWriter
{
string openingElement = "";
//The list could be simply a string, or whatever you need
List<string> fullyClosedElements = new List<string>();
public CustomHtmlWriter(StringBuilder sb) : base(new StringWriter(sb))
{
//The Rest of the tags would be explicitely closed.
fullyClosedElements.AddRange(new string[] { "br" });
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
//Generate a new line so the output wont be all in one line
WriteWhitespace("\n");
//Save the current tag
base.WriteStartElement(prefix, localName, ns);
openingElement = localName;
}
public override void WriteEndElement()
{
//Close it if needs to
if (fullyClosedElements.IndexOf(openingElement) < 0)
{
WriteFullEndElement();
}
else
{
base.WriteEndElement();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment