Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aspose-com-gists/0cdca4380fe117d2fe28ceec0f792876 to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-gists/0cdca4380fe117d2fe28ceec0f792876 to your computer and use it in GitHub Desktop.
Parse, analyze, edit, and generate Markdown in C#. Work with AST, modify structure, and process GitHub-Flavored Markdown

Markdown Processing and Manipulation in C#

This repository contains C# code examples referenced in the Aspose.HTML for .NET documentation. These gists demonstrate practical ways to load, read, create, modify, and save Markdown documents programmatically in C# using the powerful Aspose.HTML for .NET API.

What’s Inside

The gists in this collection cover:

  • Parse Markdown files into a syntax tree (AST) with MarkdownParser.
  • Traverse nodes and extract headings (text + hierarchy levels).
  • Extract tables from Markdown using TreeWalker and node filters.
  • Modify Markdown AST nodes (replace emphasis text, edit headings).
  • Create Markdown documents programmatically from scratch.
  • Generate multiple sections in a loop with headings and paragraphs.
  • Build ordered and unordered lists, including compact list generation.
  • Add bold, italic, and bold-italic text (emphasis nodes).
  • Insert blockquotes, inline code, and fenced code blocks.
  • Update paragraph content and remove list items in existing documents.
  • Work with links and images inside Markdown content.

Each example is self-contained and ready to use.

If you need practical C# snippets for parsing, creating, and editing Markdown, this gist gives you concise, production-style examples with the Aspose.HTML for .NET API. Use it as a quick reference to build Markdown generators, editors, and analyzers in .NET projects.

Related Documentation

These samples support the tutorials in the Markdown Processing and Manipulation in C# chapter of the official documentation.

Other Related Resources

How to Use

  1. Install the latest Aspose.HTML for .NET via NuGet.
  2. You can download a free trial of Aspose.HTML for .NET and use a temporary license for unrestricted access.
  3. Explore the gists in this repository and copy the relevant code to your project.
  4. Configure paths, settings, and inputs to suit your environment.

Requirements

  • .NET Platforms: .NET 5.0, .NET Framework 4.6.1+, or .NET Core 2.0+
  • Supported OS: Windows, Linux, macOS
  • Aspose.HTML for .NET
Aspose.HTML for .NET – Markdown Processing and Manipulation in C#
// Create bold and italic Markdown text in C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax factory
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Create an emphasis of type Strong (bold)
EmphasisSyntaxNode bold = mdf.Emphasis(Emphasis.Strong);
// Create an italic object add text for it
EmphasisSyntaxNode italic = mdf.Emphasis(Emphasis.Regular);
italic.AppendChild(mdf.Text("Bold Italic Text"));
// Add italic object to bold element
bold.AppendChild(italic);
// Add the bold element to the Markdown syntax tree
md.AppendChild(bold);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "italic-bold.md");
// Save MD file
md.Save(savePath);
// Add bold text to a Markdown document in C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax factory
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Create bold object add text for it
EmphasisSyntaxNode bold = mdf.Emphasis(Emphasis.Strong);
bold.AppendChild(mdf.Text("Bold in Markdown"));
// Add bold text to the Markdown syntax tree
md.AppendChild(bold);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "markdown-bold.md");
// Save MD file
md.Save(savePath);
// Create a fenced code block in Markdown using C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree markdown = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax factory
MarkdownSyntaxFactory mdf = markdown.SyntaxFactory;
// Create a start token and an end token that will frame a code block
MarkdownSyntaxToken startToken = mdf.Token(SourceText.From("```\r\n"));
MarkdownSyntaxToken endToken = mdf.Token(SourceText.From("\r\n```"));
// Create a fenced code element
FencedCodeBlockSyntaxNode fencedCodeSpan = mdf.FencedCodeBlock(startToken, null, endToken);
// Create text content for the fenced code element
fencedCodeSpan.AppendChild(mdf.Text("Source code text"));
//Add the fenced code element to MD file
markdown.AppendChild(fencedCodeSpan);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "code-block.md");
// Save MD file
markdown.Save(savePath);
// Create an image link in Markdown using C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a link node and add it to Markdown syntax tree
InlineLinkSyntaxNode link = md.SyntaxFactory.InlineLink("", "https://docs.aspose.com/html/", "");
md.AppendChild(link);
// Create an image node and add it as a link
InlineImageSyntaxNode image = md.SyntaxFactory.InlineImage("Aspose.HTML for .NET", "https://products.aspose.com/html/images/headers/aspose_html-for-net.svg", "C# HTML Parser - Documentation");
link.AppendChild(image);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "image-link.md");
// Save MD file
md.Save(savePath);
// Add inline code to Markdown using C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax factory
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Create an empty codeSpan node
CodeSpanSyntaxNode codeSpan1 = mdf.CodeSpan();
// Create text content for the codeSpan
codeSpan1.AppendChild(mdf.Text("Source code text."));
// Add codeSpan to MD document
md.AppendChild(codeSpan1);
// Add a space after the code node through a special WhiteSpace node
md.AppendChild(mdf.Whitespace());
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "markdown-inline-code.md");
// Save MD file
md.Save(savePath);
// Add italic text to a Markdown document in C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax factory
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Create an italic object add text for it
EmphasisSyntaxNode italic = mdf.Emphasis(Emphasis.Regular);
italic.AppendChild(mdf.Text("Italic in Markdown"));
// Add italic text to the Markdown syntax tree
md.AppendChild(italic);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "markdown-italic.md");
// Save MD file
md.Save(savePath);
// Create a blockquote in Markdown using C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax factory
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Create a blockquote node
BlockQuoteSyntaxNode blockQuote = mdf.BlockQuote();
// Add a leading trivia token blockquote
blockQuote.GetLinesLeadingTrivia().Add(mdf.Token(SourceText.From("> ")));
// Create a paragraph with text content
ParagraphSyntaxNode paragraph = mdf.Paragraph();
paragraph.AppendChild(mdf.Text("For blockquote creation, you should put a sign `>` before the first line of a hard-wrapped paragraph."));
// Add the paragraph to the blockquote
blockQuote.AppendChild(paragraph);
// Add the blockquote to the Markdown document
md.AppendChild(blockQuote);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "markdown-blockquote.md");
// Save MD file
md.Save(savePath);
// Add multiple Markdown headings in C# using Aspose.HTML.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create headings for levels 1-6
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
AtxHeadingSyntaxNode heading1 = mdf.AtxHeading("Heading 1 level text", 1);
AtxHeadingSyntaxNode heading2 = mdf.AtxHeading("Heading 2 level text", 2);
AtxHeadingSyntaxNode heading3 = mdf.AtxHeading("Heading 3 level text", 3);
AtxHeadingSyntaxNode heading4 = mdf.AtxHeading("Heading 4 level text", 4);
AtxHeadingSyntaxNode heading5 = mdf.AtxHeading("Heading 5 level text", 5);
AtxHeadingSyntaxNode heading6 = mdf.AtxHeading("Heading 6 level text", 6);
// Add the first heading to the Markdown syntax tree
md.AppendChild(heading1);
// Insert spacing after the first heading
md.AppendChild(mdf.Whitespace());
md.AppendChild(mdf.EmptyLine());
md.AppendChild(heading2);
md.AppendChild(mdf.Whitespace());
md.AppendChild(heading3);
md.AppendChild(mdf.Whitespace());
md.AppendChild(heading4);
md.AppendChild(mdf.Whitespace());
md.AppendChild(heading5);
md.AppendChild(mdf.Whitespace());
md.AppendChild(heading6);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "output-headers.md");
// Save MD file
md.Save(savePath);
// Insert an image into Markdown using C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax tree
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Define alternative text for the image
string altText = "Aspose.HTML for .NET logo";
// Define the image title
string label = "Aspose.HTML for .NET";
// Define the image URL
string href = "https://docs.aspose.com/html/images/aspose-html-for-net.png";
// Create the image node
InlineImageSyntaxNode image = mdf.InlineImage(altText, href, label);
// Add image into MD document
md.AppendChild(image);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "output-image.md");
// Save MD file
md.Save(savePath);
// Insert a new paragraph into an existing Markdown document in C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Specify the path to the source MD file
string input = Path.Combine(DataDir, "document.md");
// Create a MarkdownParser object
MarkdownParser parser = new MarkdownParser();
// Parse the MD document and get a syntax tree
MarkdownSyntaxTree syntaxTree = parser.ParseFile(input);
// Use SyntaxFactory to create new Markdown nodes
MarkdownSyntaxFactory syntaxFactory = syntaxTree.SyntaxFactory;
// Create an empty paragraph
ParagraphSyntaxNode paragraphSyntaxNode = syntaxFactory.Paragraph();
// Create and add newLineTrivia element for an empty line after paragraph
WhitespaceSyntaxNode newLineTrivia = syntaxFactory.NewLineTrivia();
paragraphSyntaxNode.GetTrailingTrivia().Add(newLineTrivia);
TextSyntaxNode textSyntaxNode = syntaxFactory.Text("New paragraph text.");
// Add text to the paragraph
paragraphSyntaxNode.AppendChild(textSyntaxNode);
// Insert the paragraph at the beginning of the document
syntaxTree.InsertBefore(paragraphSyntaxNode, syntaxTree.FirstChild);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "add-paragraph.md");
// Save MD file
syntaxTree.Save(savePath);
// Create nested Markdown blockquotes in C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax tree
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
BlockQuoteSyntaxNode bq = mdf.BlockQuote();
// Add leading trivia tokens for the outer blockquote
bq.GetLinesLeadingTrivia().Add(mdf.Token(SourceText.From("> ")));
// Create a paragraph and add it to the outer blockquote
ParagraphSyntaxNode par = mdf.Paragraph();
par.AppendChild(mdf.Text("The first paragraph content."));
// Append the paragraph to the outer blockquote
bq.AppendChild(par);
// Create a nested blockquote
BlockQuoteSyntaxNode bqNested = mdf.BlockQuote();
// Add leading trivia tokens for the nested blockquote
bqNested.GetLinesLeadingTrivia().Add(mdf.Token(SourceText.From(">> ")));
// Add a paragraph to the nested blockquote
ParagraphSyntaxNode par2 = mdf.Paragraph();
par2.AppendChild(mdf.Text("The nested blockQuote content."));
bqNested.AppendChild(par2);
// Append both blockquotes to the Markdown document
md.AppendChild(bq);
md.AppendChild(bqNested);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "output-nested-bq.md");
// Save MD file
md.Save(savePath);
// Create an ordered Markdown list with headings and bold text in C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax factory
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Create a new empty ordered list node
OrderedListSyntaxNode orderedList = mdf.OrderedList();
// Add the first list item with marker 1
ListItemSyntaxNode li1 = mdf.OrderedListItem(1);
orderedList.AppendChild(li1);
// Create a paragraph with text content and add it to the li1 item
ParagraphSyntaxNode paragraph = mdf.Paragraph();
AtxHeadingSyntaxNode heading = mdf.AtxHeading("The first element in the Markdown ordered list is the level 3 heading.", 3);
paragraph.AppendChild(heading);
li1.AppendChild(paragraph);
// Add the second list item with marker 2
ListItemSyntaxNode li2 = mdf.OrderedListItem(2);
orderedList.AppendChild(li2);
// Create a strong emphasis with text content and add it to the li2 item
EmphasisSyntaxNode bold = mdf.Emphasis(Emphasis.Strong);
bold.AppendChild(mdf.Text("The second item in the Markdown ordered list is in bold."));
li2.AppendChild(bold);
// Add orderedList to MD syntax tree
md.AppendChild(orderedList);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "output-odered-list.md");
// Save MD file
md.Save(savePath);
// Add two paragraphs to a Markdown document in C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Use the SyntaxFactory property to get the factory for creating the Markdown syntax tree
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Create the first paragraph
ParagraphSyntaxNode paragraph1 = mdf.Paragraph();
// Add texts to the paragraph1
paragraph1.AppendChild(mdf.Text("The first sentence of the first paragraph."));
// Add a space after the first sentence in the paragraph through a special WhiteSpace node
paragraph1.AppendChild(mdf.Whitespace());
paragraph1.AppendChild(mdf.Text("The second sentence of the first paragraph."));
// Create and add newLineTrivia element for an empty line after paragraph1
WhitespaceSyntaxNode newLineTrivia = mdf.NewLineTrivia();
paragraph1.GetTrailingTrivia().Add(newLineTrivia);
// Add the first paragraph to the document
md.AppendChild(paragraph1);
// Create the second paragraph
ParagraphSyntaxNode paragraph2 = mdf.Paragraph();
// Add texts to the paragraph2
paragraph2.AppendChild(mdf.Text("The first sentence of the second paragraph."));
// Add a space after the first sentence in the paragraph through a special WhiteSpace node
paragraph2.AppendChild(mdf.Whitespace());
paragraph2.AppendChild(mdf.Text("The second sentence of the second paragraph."));
// Add newLineTrivia element for an empty line after paragraph2
paragraph2.GetTrailingTrivia().Add(newLineTrivia);
// Add the second paragraph as the last child
md.AppendChild(paragraph2);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "markdown-paragraph.md");
// Save MD file
md.Save(savePath);
// Bold a single word in a Markdown paragraph using C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Create a Markdown syntax factory
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Create an empty paragraph
ParagraphSyntaxNode paragraph = mdf.Paragraph();
// Add texts and whitespace to the paragraph
paragraph.AppendChild(mdf.Text("The Markdown bold is used to"));
paragraph.AppendChild(mdf.Whitespace());
// Create bold object add text for it
EmphasisSyntaxNode bold = mdf.Emphasis(Emphasis.Strong);
bold.AppendChild(mdf.Text("bold"));
// Add bold text and whitespace after it to the paragraph
paragraph.AppendChild(bold);
paragraph.AppendChild(mdf.Whitespace());
// Complete the text of sentence and add to the paragraph
paragraph.AppendChild(mdf.Text("the text, and it is similar to the bold in Microsoft Word and other text formatting documents."));
// Add paragraph into MD document
md.AppendChild(paragraph);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "markdown-bold-word.md");
// Save MD file
md.Save(savePath);
// Change a Markdown heading text programmatically in C#.
// Learn more: https://docs.aspose.com/html/net/edit-markdown/
// Create a MarkdownParser for reading an existing file
MarkdownParser parser = new MarkdownParser();
// Parse the Markdown file into a syntax tree
MarkdownSyntaxTree syntaxTree = parser.ParseFile(Path.Combine(DataDir, "input.md"));
// Find the first ATX heading in the document
AtxHeadingSyntaxNode heading = null;
MarkdownSyntaxNode node = syntaxTree.FirstChild;
while (node != null)
{
if (node is AtxHeadingSyntaxNode h)
{
heading = h;
break;
}
node = node.NextSibling;
}
if (heading != null)
{
// Clear all inline content from the heading
while (heading.FirstChild != null)
{
heading.RemoveChild(heading.FirstChild);
}
// Create and append the new heading text
MarkdownSyntaxFactory mdf = syntaxTree.SyntaxFactory;
TextSyntaxNode newText = mdf.Text("Completely New Heading Text");
heading.AppendChild(newText);
// Ensure the heading ends with a newline for valid Markdown
heading.GetTrailingTrivia().Add(mdf.NewLineTrivia());
}
// Save the modified Markdown file
syntaxTree.Save(Path.Combine(OutputDir, "modified-heading.md"));
// Create an unordered Markdown list with Aspose.HTML for .NET.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create a new Markdown document with default configuration
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Get the syntax factory to build Markdown nodes
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Add an H2 heading: "## Key Features"
AtxHeadingSyntaxNode heading = mdf.AtxHeading("Key Features", 2);
// Add a newline after the heading for proper Markdown formatting
heading.GetTrailingTrivia().Add(mdf.NewLineTrivia());
md.AppendChild(heading);
// Create an unordered (bulleted) list container
UnorderedListSyntaxNode unorderedList = mdf.UnorderedList();
// Define the list item text values
string[] features = { "Parse Markdown documents", "Modify document structure", "Generate Markdown dynamically" };
// Add each feature as a list item with a paragraph
foreach (string featureText in features)
{
// Create a list item with "-" marker
ListItemSyntaxNode listItem = mdf.UnorderedListItem("-");
// Create a paragraph and add the feature text
ParagraphSyntaxNode paragraph = mdf.Paragraph();
paragraph.AppendChild(mdf.Text(featureText));
// Assemble: paragraph → list item → list
listItem.AppendChild(paragraph);
unorderedList.AppendChild(listItem);
}
// Add the completed list to the document
md.AppendChild(unorderedList);
// Save the Markdown file to disk
md.Save(Path.Combine(OutputDir, "unordered-list.md"));
// Generate a Markdown document programmatically in C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create a new Markdown document using the syntax tree API
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Add an H1 title at the top of the file
AtxHeadingSyntaxNode h1 = mdf.AtxHeading("Markdown Generation in C#", 1);
h1.GetTrailingTrivia().Add(mdf.NewLineTrivia());
md.AppendChild(h1);
// Add an introductory paragraph with multiple text nodes
ParagraphSyntaxNode intro = mdf.Paragraph();
intro.AppendChild(mdf.Text(
"This document was generated programmatically using Aspose.HTML for .NET."));
intro.AppendChild(mdf.NewLineTrivia());
intro.AppendChild(mdf.Text(
"The API allows you to build Markdown documents using a structured syntax tree."));
md.AppendChild(intro);
// Insert a blank line between sections
md.AppendChild(mdf.NewLineTrivia());
// Add an H2 section heading
AtxHeadingSyntaxNode h2 = mdf.AtxHeading("Why Use AST-Based Generation?", 2);
h2.GetTrailingTrivia().Add(mdf.NewLineTrivia());
md.AppendChild(h2);
// Add a paragraph under the second heading
ParagraphSyntaxNode paragraph = mdf.Paragraph();
paragraph.AppendChild(mdf.Text(
"Using a syntax tree ensures structural correctness and avoids manual string concatenation."));
md.AppendChild(paragraph);
// Save the Markdown file to disk
string path = Path.Combine(OutputDir, "generated-document.md");
md.Save(path);
// Build a Markdown document from scratch in C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create the MarkdownSyntaxTree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
// Use the SyntaxFactory property to get the factory for creating the Markdown syntax tree
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
AtxHeadingSyntaxNode heading2 = mdf.AtxHeading("How to create Markdown from scratch in C#?", 2);
// Add a newline after the heading
WhitespaceSyntaxNode newLineTrivia = mdf.NewLineTrivia();
heading2.GetTrailingTrivia().Add(newLineTrivia);
// Add the heading to the Markdown document
md.AppendChild(heading2);
// Create an empty paragraph
ParagraphSyntaxNode paragraph = mdf.Paragraph();
// Add texts to the paragraph
paragraph.AppendChild(mdf.Text("First, add an Aspose.HTML for .NET library reference to your C# project."));
// Add an empty line after the first sentence
paragraph.AppendChild(mdf.NewLineTrivia());
paragraph.AppendChild(mdf.Text("Then create the MarkdownSyntaxTree and use the SyntaxFactory property to get a syntax factory to create new elements."));
// Add the filled paragraph to the document
md.AppendChild(paragraph);
// Prepare a path for MD file saving
string savePath = Path.Combine(OutputDir, "create-from-scratch.md");
// Save MD file
md.Save(savePath);
// Create a structured Markdown document with multiple headings using C#.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create a new Markdown document using the syntax tree API
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Add the main H1 title to the Markdown document
AtxHeadingSyntaxNode h1 = mdf.AtxHeading("Documentation Guide", 1);
h1.GetTrailingTrivia().Add(mdf.NewLineTrivia());
md.AppendChild(h1);
// Add an H2 section heading
AtxHeadingSyntaxNode h2 = mdf.AtxHeading("Installation", 2);
h2.GetTrailingTrivia().Add(mdf.NewLineTrivia());
md.AppendChild(h2);
// Write a paragraph under the section heading
ParagraphSyntaxNode paragraph = mdf.Paragraph();
paragraph.AppendChild(mdf.Text(
"Install Aspose.HTML via NuGet Package Manager."));
md.AppendChild(paragraph);
// Save the Markdown file
md.Save(Path.Combine(OutputDir, "structured.md"));
// Extract ATX heading levels from Markdown and print a hierarchy.
// Learn more: https://docs.aspose.com/html/net/parse-and-process-markdown/
// Initialize the parser and build a syntax tree from the .md file
MarkdownParser parser = new MarkdownParser();
MarkdownSyntaxTree md = parser.ParseFile(Path.Combine(DataDir, "input.md"));
List<(int Level, string Text)> headings = new List<(int Level, string Text)>();
// Walk top-level nodes using FirstChild -> NextSibling (NodeList has no index access)
MarkdownSyntaxNode topNode = md.FirstChild;
while (topNode != null)
{
if (topNode is AtxHeadingSyntaxNode heading)
{
// Determine heading level (1–6)
int level = heading.GetOpeningTag()
.ToString()
.Count(c => c == '#');
// Collect heading text from TextSyntaxNode and WhitespaceSyntaxNode children
StringBuilder sb = new StringBuilder();
MarkdownSyntaxNode child = heading.FirstChild;
while (child != null)
{
if (child is TextSyntaxNode || child is WhitespaceSyntaxNode)
sb.Append(child.ToString());
child = child.NextSibling;
}
headings.Add((level, sb.ToString().Trim()));
}
topNode = topNode.NextSibling;
}
// Output heading hierarchy with indentation reflecting nesting depth
foreach ((int Level, string Text) headingInfo in headings)
{
int level = headingInfo.Level;
string text = headingInfo.Text;
string indent = new string(' ', (level - 1) * 2);
string marker = new string('#', level);
Console.WriteLine($"{indent}{marker} {text}");
}
// Extract GFM tables from Markdown using TreeWalker in C#.
// Learn more: https://docs.aspose.com/html/net/parse-and-process-markdown/
// Initialize the parser and build a syntax tree from the .md file
MarkdownParser parser = new MarkdownParser();
MarkdownSyntaxTree md = parser.ParseFile(Path.Combine(DataDir, "edit.md"));
// CreateTreeWalker(MarkdownSyntaxNodeFilter) traverses the full tree
// returning only nodes accepted by the filter
using TreeWalker tableWalker = md.CreateTreeWalker(new TypeFilter<TableSyntaxNode>());
MarkdownSyntaxNode current;
while ((current = tableWalker.NextNode()) != null)
{
if (current is not TableSyntaxNode table) continue;
// Iterate rows via FirstChild -> NextSibling
MarkdownSyntaxNode row = table.FirstChild;
while (row != null)
{
if (row is TableRowSyntaxNode tableRow)
{
StringBuilder sb = new StringBuilder();
MarkdownSyntaxNode cell = tableRow.FirstChild;
while (cell != null)
{
if (cell is TableCellSyntaxNode)
sb.Append($"| {cell.ToString().Trim()} ");
cell = cell.NextSibling;
}
if (sb.Length > 0)
Console.WriteLine(sb.Append('|').ToString());
}
row = row.NextSibling;
}
}
// Generate multiple Markdown sections in a loop using Aspose.HTML for .NET.
// Learn more: https://docs.aspose.com/html/net/create-markdown-documents/
// Create an empty Markdown syntax tree
MarkdownSyntaxTree md = new MarkdownSyntaxTree(new Configuration());
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
// Define section titles for the document
string[] sections = { "Installation", "Configuration", "Usage" };
// Build a heading + paragraph pair for each section
foreach (string section in sections)
{
// Create an H2 heading with the section title
AtxHeadingSyntaxNode heading = mdf.AtxHeading(section, 2);
// Add a newline after the heading for valid Markdown
heading.GetTrailingTrivia().Add(mdf.NewLineTrivia());
// Append the heading to the document tree
md.AppendChild(heading);
// Create a paragraph node for the section body
ParagraphSyntaxNode paragraph = mdf.Paragraph();
// Add dynamic text content for each section
paragraph.AppendChild(mdf.Text(
$"This section describes how to handle {section.ToLower()} in your application."));
// Append the paragraph after the heading
md.AppendChild(paragraph);
// Add a blank line between sections
md.AppendChild(mdf.NewLineTrivia());
}
// Save the generated Markdown file
md.Save(Path.Combine(OutputDir, "loop-generated.md"));
// Custom filter: accepts only nodes of type T, skips everything else.
// AcceptNode returns 1 (FILTER_ACCEPT) or 3 (FILTER_SKIP) per the NodeFilter contract.
class TypeFilter<T> : MarkdownSyntaxNodeFilter where T : MarkdownSyntaxNode
{
public override short AcceptNode(MarkdownSyntaxNode node)
=> node is T ? (short)1 : (short)3;
}
// Replace text inside Markdown emphasis nodes using C#.
// Learn more: https://docs.aspose.com/html/net/parse-and-process-markdown/
// Parse Markdown string into a full syntax tree
string markdownContent =
"# Release Notes\n\n" +
"*Aspose.HTML* is a powerful HTML processing library.\n" +
"Use *Aspose.HTML* to convert, parse, and manipulate HTML documents.\n" +
"The latest version of *Aspose.HTML* includes Markdown support.";
MarkdownParser parser = new MarkdownParser();
MarkdownSyntaxTree md = parser.Parse(markdownContent);
// SyntaxFactory is used to create new Markdown nodes
MarkdownSyntaxFactory mdf = md.SyntaxFactory;
int replacementCount = 0;
// Recursive traversal of the Markdown syntax tree
void TraverseAndReplace(MarkdownSyntaxNode node)
{
// Detect inline emphasis nodes (e.g., *text*)
if (node is EmphasisSyntaxNode emphasisNode)
{
// Ensure emphasis contains exactly one text node
if (emphasisNode.FirstChild is TextSyntaxNode textNode &&
emphasisNode.FirstChild.NextSibling == null)
{
// Extract plain text from TextSyntaxNode
string currentText = textNode.ToString().Trim();
// Perform semantic comparison instead of raw string replacement
if (currentText == "Aspose.HTML")
{
// Remove old text node
emphasisNode.RemoveChild(textNode);
// Insert new text node using SyntaxFactory
emphasisNode.AppendChild(mdf.Text("Aspose.HTML for .NET"));
replacementCount++;
}
}
}
// Pointer-based traversal (FirstChild / NextSibling pattern)
MarkdownSyntaxNode child = node.FirstChild;
while (child != null)
{
MarkdownSyntaxNode next = child.NextSibling;
TraverseAndReplace(child);
child = next;
}
}
// Start AST traversal from the root Markdown document node
TraverseAndReplace(md);
// Output statistics for debugging or logging
Console.WriteLine($"Replaced {replacementCount} occurrence(s).");
// Save modified Markdown file
md.Save(Path.Combine(OutputDir, "modified-release-notes.md"));
// Remove a list item from Markdown using Aspose.HTML for .NET.
// Learn more: https://docs.aspose.com/html/net/edit-markdown/
// Create a MarkdownParser for editing a list
MarkdownParser parser = new MarkdownParser();
// Parse the Markdown file into a syntax tree
MarkdownSyntaxTree syntaxTree = parser.ParseFile(Path.Combine(DataDir, "document.md"));
// Start from the first node
MarkdownSyntaxNode currentNode = syntaxTree.FirstChild;
UnorderedListSyntaxNode unorderedList = null;
// Traverse top-level nodes to find the first unordered list
while (currentNode != null)
{
if (currentNode is UnorderedListSyntaxNode)
{
unorderedList = (UnorderedListSyntaxNode)currentNode;
break;
}
currentNode = currentNode.NextSibling;
}
if (unorderedList != null)
{
// Get the first list item
MarkdownSyntaxNode listItem = unorderedList.FirstChild;
if (listItem != null)
{
// Remove the first list item from the list
unorderedList.RemoveChild(listItem);
}
}
// Save the modified Markdown file
syntaxTree.Save(Path.Combine(OutputDir, "modified-list.md"));
// Extract ATX heading text from a Markdown syntax tree in C#.
// Learn more: https://docs.aspose.com/html/net/parse-and-process-markdown/
// Collection for extracted heading texts
List<string> headings = new List<string>();
// Parse the Markdown file into a syntax tree
MarkdownParser parser = new MarkdownParser();
MarkdownSyntaxTree md = parser.ParseFile(Path.Combine(DataDir, "input.md"));
// Traverse top-level nodes using FirstChild / NextSibling pattern
MarkdownSyntaxNode currentNode = md.FirstChild;
while (currentNode != null)
{
// Process only ATX-style headings (# H1, ## H2, etc.)
if (currentNode is AtxHeadingSyntaxNode heading)
{
// Collect text content from heading child nodes
StringBuilder sb = new StringBuilder();
MarkdownSyntaxNode child = heading.FirstChild;
while (child != null)
{
if (child is TextSyntaxNode || child is WhitespaceSyntaxNode)
{
sb.Append(child.ToString());
}
child = child.NextSibling;
}
headings.Add(sb.ToString().Trim());
}
currentNode = currentNode.NextSibling;
}
// Output extracted headings
Console.WriteLine($"Headings found: {headings.Count}\n");
foreach (string h in headings)
{
Console.WriteLine($" {h}");
}
// Update Markdown paragraph content using Aspose.HTML for .NET.
// Learn more: https://docs.aspose.com/html/net/edit-markdown/
// Create a MarkdownParser for editing content
MarkdownParser parser = new MarkdownParser();
// Parse the Markdown file into a syntax tree
MarkdownSyntaxTree syntaxTree = parser.ParseFile(Path.Combine(DataDir, "document.md"));
// Start from the first node in the document
MarkdownSyntaxNode currentNode = syntaxTree.FirstChild;
ParagraphSyntaxNode paragraph = null;
// Traverse top-level nodes to find the first paragraph
while (currentNode != null)
{
if (currentNode is ParagraphSyntaxNode)
{
paragraph = (ParagraphSyntaxNode)currentNode;
break;
}
currentNode = currentNode.NextSibling;
}
if (paragraph != null)
{
// Remove existing paragraph content
while (paragraph.FirstChild != null)
{
paragraph.RemoveChild(paragraph.FirstChild);
}
// Get the syntax factory for new nodes
MarkdownSyntaxFactory mdf = syntaxTree.SyntaxFactory;
// Create new paragraph text
TextSyntaxNode newText = mdf.Text("This paragraph was updated programmatically using Aspose.HTML for .NET.");
// Append updated text to the paragraph
paragraph.AppendChild(newText);
}
// Save the modified Markdown file
syntaxTree.Save(Path.Combine(OutputDir, "modified-paragraph.md"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment