Read The Times Australia

Daily Bulletin

Converting HTML to Markdown with Upmark

  • Written by: Josh Bassett, Data Platform Technical Lead, The Conversation

Here at The Conversation we run a Job Board that requires parsing a whole bunch of job descriptions in HTML and converting them to Markdown. When we originally built the Job Board we looked around for a HTML to Markdown converter library written in Ruby but unfortunately we couldn’t find one, so we built our own: Upmark.

Upmark allows you to easily convert HTML documents to Markdown format:

require "upmark"
html = "<p>messenger <strong>bag</strong> skateboard</p>"
markdown = Upmark.convert(html)
puts markdown
"messenger **bag** skateboard"

It can handle most HTML tags and anything that isn’t able to be converted to Markdown is passed through as HTML.

How does it work?

Upmark does all the heavy lifting using a parser transformer built using the excellent Parslet library. Parslet allows you to define a grammar in plain ruby that is used to parse a document into a syntax tree. The syntax tree can then be arbitrarily transformed, in our case it is transformed into a Markdown document.

The whole process looks something like this:

image Author provided Parse it! The first phase of the process is parsing the input into a syntax tree. To parse a HTML document we first need to define a grammar. A grammar contains the individual rules for parsing the different parts of a document. Rules for parsing simpler elements can be combined together to parse more complex structures. Parslet provides us with the Parslet::Parser class which we extend to define parser: class MyParser < Parslet::Parser # all the rules go here end In the case of Upmark, we first define rules for parsing the more complex parts of a HTML document, like an element. The rule for parsing an element is then decomposed into rules for parsing tags and attributes. These rules are then further broken down into combinations of simpler rules for text, numbers, and whitespace. Consider the following snippet of HTML: <p>hello world!</p> <img src="lol.gif" /> <ol> <li>one</li> <li>two</li> <li>three</li> </ol> This document is just a series of HTML elements, so the first rule we define might be: rule(:element) do start_tag.as(:start_tag) >> # e.g. "<p>" children.as(:children) >> end_tag.as(:end_tag) # e.g. "</p>" end This rule says that in order to parse an element we need a start_tag, some children, and finally an end_tag. The as modifiers define how they are labelled in the resulting syntax tree. Okay, so now what? Let’s break it down further and add the next rule to our parser. To parse a start_tag we need a < character, a name, zero or more attributes (separated by whitespace), some optional whitespace, and finally a > character. rule(:start_tag) do str('<') >> name.as(:name) >> (space >> attribute).repeat.as(:attributes) >> space? >> str('>') end According to the XML spec, a name is just a string limited to a particular range of characters: rule(:name) do match(/[a-zA-Z_:]/) >> match(/[\w:\.-]/).repeat end Here are the rules for parsing whitespace: rule(:space) { match(/\s/).repeat(1) } rule(:space?) { space.maybe } I’ll leave defining the rules for parsing children and attributes as an exercise for the reader (or you can cheat and just look in the Upmark source code). Finally, this is how we apply our parser to the input: tree = MyParser.new.parse(html) Once our parser is applied to a document, a syntax tree is generated. Transform it! The second phase of the whole process is to transform the syntax tree into some desired output. Parslet syntax trees are represented as an array of nested hashes. For example: tree = [ { element: { name: "img", attributes: [{name: "src", value: "http://example.com/lol.gif"}], children: [] } } ] Given the above syntax tree, let’s write a transform which traverses the syntax tree and converts it to Markdown. Again, Parslet makes transforming easier for us by providing the Parslet::Transform class to extend: class MyTransform < Parslet::Transform rule( element: { name: "img", attributes: subtree(:attributes) } ) do |img| src = img[:attributes].find {|attribute| attribute["name"] == "src" }["value"] "![](#{src})" end end The MyTransform transform matches an img element with a subtree of attributes. It then plucks out the src attribute and returns the Markdown for an image. This is how we apply the transform to the syntax tree: markdown = MyTransform.new.apply(tree) puts markdown "![](http://example.com/lol.gif)" Turtles all the way down So how did we write a parser that converts an entire HTML document to Markdown? The answer is simple: it’s turtles all the way down. By combining multiple rules and transforms, we can break a big problem down into a series of smaller problems. Hopefully this gives you some insight into how to write your own parser using Parslet, and if you happen to need a handy HTML to Markdown converter then please check out Upmark.

Authors: Josh Bassett, Data Platform Technical Lead, The Conversation

Read more http://theconversation.com/converting-html-to-markdown-with-upmark-65788

Business News

Designing Eco-Friendly Custom Water Bottles for Your Next Event

The Evolution of Sustainable Event Merchandise Event planning has undergone a massive transformation over the last decade. Gone are the days when organizers could hand out cheap, single use plastic...

Daily Bulletin - avatar Daily Bulletin

Why Choosing a Professional Florist Melbourne Makes Flower Delivery Impactful

Flowers have a great power to speak when humans cannot express their feelings with right words. Flowers are the best gifts when you are celebrating a birthday or welcoming a newborn child into your fa...

Daily Bulletin - avatar Daily Bulletin

The Business Case for Choosing Australian Fabricators Over Imported Alternatives

For a long time, you might have defaulted to overseas suppliers when sourcing fabricated metal components for a project. The unit price was lower on paper, and the maths seemed straightforward. That...

Daily Bulletin - avatar Daily Bulletin

Australian organisations are relying on business continuity plans built for a far more predictable world

Tariff escalations, supply chain fragility, geopolitical events, and the ongoing threat of cyber disruption have reshaped the risk environment facing Australian organisations. The problem is that ma...

Daily Bulletin - avatar Daily Bulletin

How to Rent a Car for Uber in Melbourne: What Every New Driver Needs to Know

Starting out as an Uber driver in Melbourne is not as complicated as it sounds but getting the vehicle right is where most new drivers get stuck. Uber has strict requirements around vehicle age, condi...

Daily Bulletin - avatar Daily Bulletin

When Should You Speak to a Lawyer About a Legal Issue?

Legal issues can begin with a simple question, then become harder to manage once formal steps are involved. Many people wait until a matter feels urgent before seeking guidance, even though earlier ...

Daily Bulletin - avatar Daily Bulletin

The strategic rise of Bali as Australia’s next essential healthcare support hub

As Australian healthcare providers grapple with unprecedented operational bottlenecks, a new nearshore model is quietly transforming patient care delivery. Forward-thinking organisations,  including...

Daily Bulletin - avatar Daily Bulletin

Cost Savings and Benefits of Using Used Pallets in Logistics

In today’s competitive logistics and supply chain industry, businesses are constantly looking for ways to reduce operational costs without compromising efficiency and reliability. One of the most prac...

Daily Bulletin - avatar Daily Bulletin

How Fulfilment Services in Australia Help Businesses Scale Efficiently

The growth of e-commerce and modern retail has transformed customer expectations. Consumers now expect fast shipping, accurate order processing, and seamless delivery experiences regardless of where...

Daily Bulletin - avatar Daily Bulletin

The Daily Magazine

Top 4 Wheelchair Ramp Providers in the Boulder Area

Finding the right wheelchair ramp in Boulder will feel like a turning point. Whether you are plann...

Thermoplastic vs. Paint: The True Long-Term Cost Comparison

Line marking looks like a simple line item on a school maintenance budget, until the true cost of ...

Why Vetting Beats Volume: The Real Story Behind Australia's Growing Applicant Pools

On paper, hiring should be getting easier. Job ads across the country are pulling in more applicat...

Moving Out of a Rental in Melbourne? A Practical Moving Checklist

Moving out of a rental in Melbourne is one of those things that always feels further away than it ...

Why a Cordless Rebar Tying Machine Is a Smart Investment for Australian Construction Projects

Tying reinforcing steel by hand means spending hours bent over while making the same twisting moti...

How to Get a Document Notarised in Sydney: What to Bring, What It Costs and How Long It Takes

If an overseas bank, embassy, university, employer or land registry has asked you for a notarised ...

The 2026 Used-Car Market

For a few strange years, the used-car market rewrote its own rules. Supply shortages sent second-h...

Why CCTV Alone Is Not Enough for Modern Business Security

Cameras are usually the initial step that companies take to strengthen their physical security. If...

Why Every Workplace Should Take Emergency Preparedness Seriously

Emergency planning is one of those things many workplaces know they should think about, but it oft...