SoFunction
Updated on 2025-03-03

Java two ways to parse Markdown document format

Method 1: CommonMark

1. Introduction

CommonMark is a specification that defines a concise and consistent Markdown format syntax. It is designed to provide a standard way to parse and render Markdown documents.

2. Tutorial

  • Introducing Maven dependencies
  • commonmark-ext-gfm-tables: The dependency used to implement table parsing
 <dependency>
            <groupId></groupId>
            <artifactId>commonmark</artifactId>
            <version>0.20.0</version>
        </dependency>
        <!-- Implement table analysis -->
        <dependency>
            <groupId></groupId>
            <artifactId>commonmark-ext-gfm-tables</artifactId>
            <version>0.20.0</version>
        </dependency>

JAVA code example

    public static String parseMarkdownCommonmark(String markdownContent) {
        //Analysis table        List<Extension> extensions = (());
         parser = ().extensions(extensions).build();
        Node document = (markdownContent);
         renderer = ().extensions(extensions).build();
        return (document);
    }

3. Problem

Unable to implement directory parsing, that is, in the Markdown document[TOC]Of course, Flexmark solves this problem very well.

Method 2: Flexmark

1. Introduction

Flexmark-Java is a Java library based on the CommonMark specification for parsing and rendering Markdown documents. It provides a flexible, easy-to-use API that customizes the behavior of parsing and rendering.

2. Use examples

  • Introducing Maven dependencies
  • The latest version is 0.64.8, supports java11 and higher, does not support java8
  <dependency>
            <groupId></groupId>
            <artifactId>flexmark-all</artifactId>
            <version>0.62.2</version>
            <scope>compile</scope>
        </dependency>

Java code

public static String parseMarkdownFlexmark(String markdown) {
        MutableDataSet options = new MutableDataSet();
        //TOC directory analysis, table analysis        (, ((), ()));
        Parser parser = (options).build();
        Document document = (markdown);
        HtmlRenderer renderer = (options).build();
        return (document);
    }

This is the end of this article about Java parsing Markdown document format. For more related Java Markdown document format content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!