← Back to archive

Repo of the Day

locize/xliff

Published: Nov 23, 2021

Open repository ↗

Convert between xliff style xml and json files

Summary

locize/xliff is a JavaScript library that converts between XLIFF (the XML-based translation interchange format) and plain JavaScript objects, with support for XLIFF 1.2 and 2.x. It also provides helpers for extracting source or target strings, building XLIFF documents from key/value pairs, and handling inline placeholders such as {name} inside translation strings.

What it is useful for

This library is useful when an application needs to read translations out of an XLIFF file produced by a translation tool, or to write translations back into XLIFF for handoff to translators or CAT (computer-assisted translation) systems. It fits build pipelines that import or export localization files, server-side services that process XLIFF, and code that needs to round-trip between JSON and XLIFF without losing structure. The library also parses XLIFF 2.1 and 2.2 files permissively, keeping unknown attributes and elements (for example mda:metadata) on the JS model so they are not silently dropped.

How engineers can use it

Install via npm as documented:

npm install --save xliff

Then import either the package entry or individual functions:

import xliff2js from 'xliff/xliff2js'
import js2xliff from 'xliff/js2xliff'

A typical XLIFF 2.0 string with <file>, <unit>, <source>, and <target> elements parses into a JSON shape with resources keyed by namespace, plus sourceLanguage and targetLanguage. The same shape can be passed back to js2xliff to produce an XLIFF string.

For simpler workflows, createxliff (or createxliff12 for 1.2) takes a source language, target language, a source key/value map, a target key/value map, and a namespace, and returns an XLIFF string. sourceOfjs and targetOfjs flatten a parsed object into just the source or target values keyed by translation key, which is handy when feeding an existing i18n resource.

Inline elements like <g id="name" ctype="x-python-brace-param">{name}</g> are preserved either as structured objects inside arrays, or as compact string tokens when passing inlineAsString: true to xliff12ToJs/xliff2js and the corresponding exporters. The makeInlineElement(ElementTypes.GenericSpan, { ctype: 'x-python-brace-param' }, '{name}') helper builds these objects programmatically.

Limitations noted in the README: only the inline element types in the supported table (Standalone, GenericSpan, GenericSpanStart, GenericSpanEnd, Span, SpanStart, SpanEnd) are handled, and a 1.2 → JS → 2.0 → JS → 1.2 round-trip will convert Native inline elements into Generic elements because XLIFF 2.0 has no Native type. The 2.2-only constructs (plural, gender, select, headerExtras) require the targetXliffVersion: '2.2' opt-in.