Abstract Syntax Tree - Nested objects #514

Closed
opened 2026-01-29 14:38:31 +00:00 by claunia · 2 comments
Owner

Originally created by @aviveldan on GitHub (Mar 17, 2022).

Hi,
Would be glad for your help. Not sure if it is a feature request or silly question.

I am trying to work with the AST.

var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
var result = Markdown.Parse(
@"
# Hello there :)
| Item         | Price     | # In stock |
|--------------|-----------|------------|
| Juicy Apples | 1.99      | *7*        |
| Bananas      | **1.89**  | 5234       |
", pipeline);

Now I want to check if there are nodes within the group of types: bold, italic, header
I tried using the Enumerator:
var i = result.GetEnumerator();
But the MoveNext method doesn't go through nested nodes, and therefore I need to check the type of the current object:
i.Current.GetType()
and then use dynamic variable and casting if it is in the list of the objects that can have children objects...
I am pretty sure this isn't how I should traverse the tree.
Any ideas how to do that efficiently?

Thanks in advance :)

Originally created by @aviveldan on GitHub (Mar 17, 2022). Hi, Would be glad for your help. Not sure if it is a feature request or silly question. I am trying to work with the AST. ```c# var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build(); var result = Markdown.Parse( @" # Hello there :) | Item | Price | # In stock | |--------------|-----------|------------| | Juicy Apples | 1.99 | *7* | | Bananas | **1.89** | 5234 | ", pipeline); ``` Now I want to check if there are nodes within the group of types: bold, italic, header I tried using the Enumerator: `var i = result.GetEnumerator();` But the MoveNext method doesn't go through nested nodes, and therefore I need to check the type of the current object: `i.Current.GetType()` and then use dynamic variable and casting if it is in the list of the objects that can have children objects... I am pretty sure this isn't how I should traverse the tree. Any ideas how to do that efficiently? Thanks in advance :)
claunia added the question label 2026-01-29 14:38:31 +00:00
Author
Owner

@MihaZupan commented on GitHub (Mar 17, 2022):

I recommend the document.Descendants() or document.Descendants<SyntaxType>() API.

foreach (EmphasisInline emphasis in document.Descendants<EmphasisInline>())
{
    // ...
}
@MihaZupan commented on GitHub (Mar 17, 2022): I recommend the `document.Descendants()` or `document.Descendants<SyntaxType>()` API. ```c# foreach (EmphasisInline emphasis in document.Descendants<EmphasisInline>()) { // ... } ```
Author
Owner

@aviveldan commented on GitHub (Mar 20, 2022):

Thanks for the quick response.
It works :)

@aviveldan commented on GitHub (Mar 20, 2022): Thanks for the quick response. It works :)
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/markdig#514