Skip to content

HTML to Markdown Converter — C# source

Convert HTML fragments and articles into clean Markdown: headings, emphasis, links, images, lists, quotes and code blocks, all processed locally in your browser with a shareable link.

This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// html-to-markdown — supported HTML subset → Markdown converter.
//
// Language: C# (.NET, standard library only).
// CosmoDev polyglot showcase port of the `html-to-markdown` tool.
// Ported from src/lib/html-to-markdown.ts (the canonical TypeScript lib);
// the Go CLI twin lives at cli/html-to-markdown/html-to-markdown.go.
//
// A hand-rolled single-scan tag parser (no DOM) builds a node forest, then a
// renderer emits Markdown blocks: h1-h6, p/div/blockquote, pre fences with
// the language taken from class="language-*", ul/ol with 2-space (ul) and
// 4-space (ol) nested indent, hr, br as two-spaces-newline; inline marks
// strong/b/em/i/del/s/code render empty emphasis as nothing, links keep
// verbatim titles, images decode alt/src. Unknown tags are transparent,
// stray closers are ignored, unclosed tags auto-close at EOF, and text nodes
// backslash-escape \ ` * _ [ ]. A '<' with no closing '>' is the one error
// ("Unclosed tag").
//
// Entities decode via System.Net.WebUtility.HtmlDecode — the stdlib WHATWG
// table (the .NET counterpart of the TS lib's decodeHtml and Go's
// html.UnescapeString): full named coverage plus numeric decimal/hex,
// single pass, no double-decode ("x &amp;lt; y" stays "x &lt; y"; a handful
// of legacy semicolon-less names decode too — an inherited stdlib quirk).
//
// display source — part of CosmoDev's polyglot tool pages.
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;

static class HtmlToMarkdownTool
{
    /// <summary>Mirrors HtmlToMarkdownResult in the TS lib: on success Output
    /// is set and Error is null; on failure Output is empty. Empty or
    /// whitespace-only input is NOT an error — the tool shows nothing.</summary>
    public sealed record Result(string Output, string? Error);

    private const string UnclosedTag = "Unclosed tag";

    /// <summary>VOID in the TS lib — tags that never open a scope.</summary>
    private static readonly HashSet<string> VoidTags = new()
    {
        "br", "hr", "img", "meta", "link", "input", "source",
    };

    /// <summary>BLOCK_TAGS in the TS lib — tags rendered as Markdown blocks.</summary>
    private static readonly HashSet<string> BlockTags = new()
    {
        "p", "div", "blockquote", "pre", "ul", "ol", "hr",
        "h1", "h2", "h3", "h4", "h5", "h6",
    };

    private static readonly Regex TagNameRe = new("^([a-zA-Z][a-zA-Z0-9-]*)", RegexOptions.Compiled);
    private static readonly Regex AttrRe = new("([a-zA-Z-]+)(?:\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]+))?", RegexOptions.Compiled);
    private static readonly Regex LangClassRe = new("language-([\\w-]+)", RegexOptions.Compiled);
    private static readonly Regex MdEscapeRe = new("[\\\\`*_\\[\\]]", RegexOptions.Compiled);

    // .NET \s is Unicode-aware (covers U+00A0 like JS \s), so the TS twin's
    // whitespace-collapse pass needs no extra NBSP normalization here.
    private static readonly Regex WsRunRe = new("\\s+", RegexOptions.Compiled);

    /// <summary>One forest node: text (IsElem false) or element.</summary>
    private sealed class Node
    {
        public bool IsElem;
        public string Text = "";
        public string Tag = "";
        public Dictionary<string, string> Attrs = new();
        public List<Node> Children = new();

        public static Node Text(string t) => new() { Text = t };
        public static Node Elem(string tag) => new() { IsElem = true, Tag = tag };
    }

    /// <summary>One pass via the stdlib WHATWG table; malformed refs pass through.</summary>
    private static string DecodeEntities(string s) => WebUtility.HtmlDecode(s);

    /// <summary>Backslash-escape the Markdown-significant \ ` * _ [ ].</summary>
    private static string EscapeMarkdown(string s) => MdEscapeRe.Replace(s, "\\$&");

    /// <summary>Collapse any run of whitespace to a single space — the TS
    /// .replace(/\s+/g, ' ') pass.</summary>
    private static string CollapseWhitespace(string s) => WsRunRe.Replace(s, " ");

    /// <summary>Append sink: the current open element's children, else the roots.</summary>
    private static List<Node> Top(List<Node> roots, List<Node> stack) =>
        stack.Count > 0 ? stack[^1].Children : roots;

    /// <summary>Parse into a node forest. Attribute values may be double-quoted,
    /// single-quoted or bare; a quoted value may contain '>'. Returns null
    /// roots with the "Unclosed tag" error when a '<' has no closing '>'.</summary>
    private sealed record ParseResult(List<Node>? Roots, string? Error);

    private static ParseResult ParseHtml(string raw)
    {
        var roots = new List<Node>();
        var stack = new List<Node>();
        int i = 0;
        while (i < raw.Length)
        {
            int lt = raw.IndexOf('<', i);
            if (lt == -1)
            {
                Top(roots, stack).Add(Node.Text(raw[i..]));
                break;
            }
            if (lt > i) Top(roots, stack).Add(Node.Text(raw[i..lt]));
            // Find the tag's '>', skipping quoted attribute values.
            int j = lt + 1;
            char quote = '\0';
            while (j < raw.Length && (raw[j] != '>' || quote != '\0'))
            {
                char c = raw[j];
                if (quote == '\0' && (c == '"' || c == '\'')) quote = c;
                else if (quote != '\0' && c == quote) quote = '\0';
                j++;
            }
            if (j >= raw.Length) return new ParseResult(null, UnclosedTag);
            string inner = raw[(lt + 1)..j].Trim();
            i = j + 1;

            if (inner.StartsWith("!--", StringComparison.Ordinal)) continue; // comment
            if (inner.StartsWith("!", StringComparison.Ordinal)) continue; // doctype
            bool closing = inner.StartsWith("/", StringComparison.Ordinal);
            string body = closing ? inner[1..] : Regex.Replace(inner, "/$", "");
            var nm = TagNameRe.Match(body);
            if (!nm.Success) continue; // not a real tag — browsers would show it as text; we drop it
            string tag = nm.Groups[1].Value.ToLowerInvariant();

            if (closing)
            {
                for (int k = stack.Count - 1; k >= 0; k--)
                {
                    if (stack[k].Tag == tag)
                    {
                        stack.RemoveRange(k, stack.Count - k);
                        break;
                    }
                }
                continue;
            }

            var elem = Node.Elem(tag);
            foreach (Match am in AttrRe.Matches(body))
            {
                // Values stay RAW here; href/src/alt are entity-decoded at
                // use, titles stay verbatim. The strip mirrors TS
                // am[2].slice(1, -1): quoted values lose their quotes, bare
                // values lose their first and last characters (same quirk
                // the Go twin keeps for lock-step).
                string v = am.Groups[2].Value;
                elem.Attrs[am.Groups[1].Value.ToLowerInvariant()] = v.Length >= 2 ? v[1..^1] : "";
            }
            Top(roots, stack).Add(elem);
            if (!VoidTags.Contains(tag) && !body.EndsWith("/", StringComparison.Ordinal)) stack.Add(elem);
        }
        return new ParseResult(roots, null);
    }

    private static bool IsBlock(Node n) => n.IsElem && BlockTags.Contains(n.Tag);

    /// <summary>Inline content of one block: marks, links, images, escaped text.</summary>
    private static string RenderInline(List<Node> nodes)
    {
        var sb = new System.Text.StringBuilder();
        foreach (var n in nodes)
        {
            if (!n.IsElem)
            {
                sb.Append(CollapseWhitespace(EscapeMarkdown(DecodeEntities(n.Text))));
            }
            else
            {
                switch (n.Tag)
                {
                    case "br":
                        sb.Append("  \n");
                        break;
                    case "strong" or "b":
                    {
                        string inner = RenderInline(n.Children).Trim();
                        if (inner.Length > 0) sb.Append("**").Append(inner).Append("**"); // empty emphasis renders as nothing
                        break;
                    }
                    case "em" or "i":
                    {
                        string inner = RenderInline(n.Children).Trim();
                        if (inner.Length > 0) sb.Append('*').Append(inner).Append('*');
                        break;
                    }
                    case "del" or "s":
                    {
                        string inner = RenderInline(n.Children).Trim();
                        if (inner.Length > 0) sb.Append("~~").Append(inner).Append("~~");
                        break;
                    }
                    case "code":
                    {
                        string inner = RenderInline(n.Children).Trim();
                        if (inner.Length > 0) sb.Append('`').Append(inner).Append('`');
                        break;
                    }
                    case "a":
                    {
                        string href = DecodeEntities(n.Attrs.GetValueOrDefault("href", ""));
                        string title = n.Attrs.GetValueOrDefault("title", "").Length > 0
                            ? " \"" + n.Attrs["title"] + "\"" : "";
                        string label = RenderInline(n.Children).Trim();
                        if (label.Length == 0) label = href;
                        sb.Append('[').Append(label).Append("](").Append(href).Append(title).Append(')');
                        break;
                    }
                    case "img":
                    {
                        string alt = EscapeMarkdown(DecodeEntities(n.Attrs.GetValueOrDefault("alt", ""))).Trim();
                        sb.Append("![").Append(alt).Append("](")
                            .Append(DecodeEntities(n.Attrs.GetValueOrDefault("src", ""))).Append(')');
                        break;
                    }
                    default:
                        sb.Append(RenderInline(n.Children)); // span and unknown tags are transparent
                        break;
                }
            }
        }
        return sb.ToString();
    }

    /// <summary>Concatenate the entity-decoded text under nodes (pre content only).</summary>
    private static string TextOf(List<Node> nodes)
    {
        var sb = new System.Text.StringBuilder();
        foreach (var c in nodes)
        {
            sb.Append(c.IsElem ? TextOf(c.Children) : DecodeEntities(c.Text));
        }
        return sb.ToString();
    }

    /// <summary>Render a sequence of nodes as Markdown blocks.</summary>
    private static List<string> RenderBlocks(List<Node> nodes)
    {
        var outp = new List<string>();
        var para = new List<Node>();
        void Flush()
        {
            if (para.Count > 0)
            {
                string text = RenderInline(para).Trim();
                if (text.Length > 0) outp.Add(text);
                para.Clear();
            }
        }
        foreach (var n in nodes)
        {
            if (!IsBlock(n))
            {
                para.Add(n);
                continue;
            }
            Flush();
            switch (n.Tag)
            {
                case "hr":
                    outp.Add("---");
                    break;
                case "p":
                {
                    string text = RenderInline(n.Children).Trim();
                    if (text.Length > 0) outp.Add(text);
                    break;
                }
                case "div":
                    outp.AddRange(RenderBlocks(n.Children));
                    break;
                case "blockquote":
                {
                    string inner = string.Join("\n\n", RenderBlocks(n.Children));
                    var lines = new List<string>();
                    foreach (string l in inner.Split('\n'))
                    {
                        lines.Add(l.Length > 0 ? "> " + l : ">");
                    }
                    outp.Add(string.Join("\n", lines));
                    break;
                }
                case "pre":
                {
                    Node? codeElem = null;
                    foreach (var c in n.Children)
                    {
                        if (c.IsElem && c.Tag == "code") { codeElem = c; break; }
                    }
                    string lang = "";
                    if (codeElem != null)
                    {
                        var lm = LangClassRe.Match(codeElem.Attrs.GetValueOrDefault("class", ""));
                        if (lm.Success) lang = lm.Groups[1].Value;
                    }
                    string body = Regex.Replace(TextOf((codeElem ?? n).Children), "\n+$", "");
                    outp.Add("```" + lang + "\n" + body + "\n```");
                    break;
                }
                case "ul" or "ol":
                    outp.Add(RenderList(n, 0));
                    break;
                default: // h1-h6
                {
                    int level = n.Tag.Length >= 2 && n.Tag[1] >= '1' && n.Tag[1] <= '6'
                        ? n.Tag[1] - '0' : 0;
                    outp.Add(new string('#', level) + " " + RenderInline(n.Children).Trim());
                    break;
                }
            }
        }
        Flush();
        return outp;
    }

    /// <summary>ul/ol at nesting depth: 2-space indent under ul, 4-space under
    /// ol, numbering restarted per list.</summary>
    private static string RenderList(Node list, int depth)
    {
        var items = new List<Node>();
        foreach (var c in list.Children)
        {
            if (c.IsElem && c.Tag == "li") items.Add(c);
        }
        bool ordered = list.Tag == "ol";
        var lines = new List<string>();
        for (int idx = 0; idx < items.Count; idx++)
        {
            var li = items[idx];
            string marker = ordered ? (idx + 1) + "." : "-";
            string indent = new string(' ', depth == 0 ? 0 : ordered ? 4 : 2);
            // Split li children into inline content + nested lists.
            var inline = new List<Node>();
            var nested = new List<string>();
            foreach (var c in li.Children)
            {
                if (c.IsElem && (c.Tag == "ul" || c.Tag == "ol")) nested.Add(RenderList(c, depth + 1));
                else inline.Add(c);
            }
            string text = RenderInline(inline).Trim();
            lines.Add(text.Length > 0 ? $"{indent}{marker} {text}" : $"{indent}{marker}");
            lines.AddRange(nested);
        }
        return string.Join("\n", lines);
    }

    /// <summary>Convert the supported HTML subset to Markdown. Never throws —
    /// the result carries output/error, mirroring HtmlToMarkdownResult.</summary>
    public static Result Convert(string raw)
    {
        if (raw.Trim().Length == 0) return new Result("", null);
        var parsed = ParseHtml(raw);
        if (parsed.Error != null) return new Result("", parsed.Error);
        return new Result(string.Join("\n\n", RenderBlocks(parsed.Roots!)), null);
    }

    static void Main()
    {
        var r = Convert("<h1>Title</h1><p>a &amp; <b>b</b></p><ul><li>x<ul><li>y</li></ul></li></ul>");
        Console.WriteLine(r.Output);
        Console.WriteLine("error: " + (r.Error ?? "null"));
    }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →