Urgent.News

What's breaking now, across thousands of outlets.

Tech

Building XML-to-Markdown Converters: Algorithms and Edge Cases

Converting XML documents to Markdown sounds simple until you actually try it. Here's what we learned building a converter for Turkey's UYAP legal document format. The Core Algorithm XML DOM → Walk tree → Emit Markdown tokens → Join & clean Step 1: Parse XML const parser = new DOMParser (); const doc = parser . parseFromString ( xmlText , " text/xml " ); // Always check for parse errors! const err…

Converting XML documents to Markdown may seem straightforward, but in practice it presents various challenges. This is what we discovered while developing a converter for Turkey's UYAP legal document format.

Step 1 involves parsing the XML text using a DOM parser. We must always verify for parse errors to ensure the XML is valid. If parsing fails, an error is thrown with a message indicating the issue.

After parsing, we traverse the element tree. For each child element, we use a switch statement to determine how to convert that particular element type to Markdown. Paragraphs, tables, and images are handled separately through dedicated functions, while other elements are ignored.

The crux of the conversion lies in formatting inline text elements. XML attributes can be mapped to Markdown syntax rules. For instance, if an element has both bold and italic attributes, it will be converted to a Markdown text with triple asterisks. Similarly, elements with just bold or italic attributes will be converted accordingly. If no formatting attributes are present, the text is returned as is.

Edge cases arise when dealing with overlapping formatting elements. XML allows separate content elements for such cases, but we must ensure our Markdown output doesn't end up broken or malformed, like in the case of mixed bold and italic attributes.

Detecting headings in UYAP XML is challenging since the format doesn't provide explicit heading elements. To overcome this, we implemented heuristics. The function `isHeading` checks if a paragraph element is a heading based on its font size, boldness, and alignment attributes. If the conditions are met—such as a large font size paired with bold text or centered text, the function returns the corresponding heading level.

However, if these conditions aren't met, the function returns zero, indicating that the element is not a heading.

Lastly, converting XML tables to Markdown requires us to know the column count beforehand. This is achieved by first retrieving all row elements from the table node. For each row, we extract all cell elements and convert them into Markdown table cells. The resulting cells are then assembled into a markdown table format.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Monday 21 September →