Markup-aware translation workflows for XML, HTML and MJML
Extract to PO, translate anywhere (gettext, Weblate, Crowdin, CAT tools via XLIFF), compile back β without ever losing a translation.
xml2po streamlines localization for XML-flavored templates: it extracts
translatable strings into standard PO files, merges translator work back
without data loss, and compiles translations into the original documents
while preserving whitespace, entities and markup byte-for-byte.
- Inline markup placeholders β
<p>Hello <b>bold</b> world</p>is one msgid:Hello <b>bold</b> world. Sentences stay whole, translators reorder words freely, and compilation re-inserts the original tags (attributes included). Translations whose markup doesn't match are rejected safely and counted in the report. - ITS-lite semantics β HTML5
translate="no|yes"andits:translateare honored by default. Non-translatable inline content (<span translate="no">ACME</span>) is kept verbatim inside the msgid, itstool-style. - Lossless PO layer β full plural round-trip (
msgstr[N]),#, flags(fuzzy translations are skipped unless you ask for them),#|previous msgids,#~obsolete entries preserved across merges, typed header metadata (PoMetadata), and strict duplicate detection. - CI gates β
checkfails on catalog drift or low coverage;stats --json/check --jsonfor machine-readable pipelines. - XLIFF 1.2 bridge β exchange catalogs with Trados, memoQ, Lokalise,
Transifex and friends (
catalog_to_xliff/catalog_from_xliff). - WebAssembly ready β compiles to
wasm32-unknown-unknownfor in-browser localization workflows. - Error messages with line:column β XML failures point at the exact position, not a byte offset.
cargo install xml2po[dependencies]
xml2po = "0.3"# Extract translatable strings (inline placeholders on by default)
xml2po extract src/*.html --output messages.po
# Refresh a catalog after source changes: translations are kept,
# removed strings become #~ obsolete entries
xml2po update src/*.html --output messages.po
# Compile a translated document
xml2po compile --input page.html --po fr.po --output fr.html
# CI: fail when the catalog drifts or coverage drops below 90%
xml2po check --min-coverage 90 messages.po src/*.html
xml2po stats --json messages.pouse xml2po::{extract_messages, apply_translations, get_strategy};
use xml2po::po::PoCatalog;
let content = r#"<p>Hello <b>bold</b> world</p>"#;
let strategy = get_strategy("html")?;
// One message per sentence β inline tags folded in.
let messages = extract_messages(content, "page.html", strategy)?;
assert_eq!(messages[0].msgid, "Hello <b>bold</b> world");
// Translate and compile: the original <b> tag is re-inserted.
let mut catalog = PoCatalog::from_messages(&messages);
catalog.set_translation(
xml2po::message::CatalogKey::new(None, "Hello <b>bold</b> world"),
"Hola <b>negrita</b> mundo",
);
let translated = apply_translations(content, &catalog.translations(), strategy)?;
assert_eq!(translated, "<p>Hola <b>negrita</b> mundo</p>");During extraction, inline elements (b, em, span, a, strong,
br, β¦) fold into the surrounding message as attribute-free tags, and
literal text is XML-escaped (& β &, < β <) so msgids stay
unambiguous:
<p>Name: <span translate="no">ACME</span> inc.</p>msgid "Name: <span translate=\"no\">ACME</span> inc."During compilation the tag sequences of msgid and msgstr must match (same tags, same order). Text between tags may be reordered, split or merged freely β word order can change between languages. Each translation tag is replaced by the corresponding source tag with its original attributes:
<p>Name: <span translate="no">ACME</span> GmbH</p>| Translation | Result |
|---|---|
Name: <span translate="no">ACME</span> Ltd. |
β applied |
Name: <span>ACME</span> Ltd. (missing attr) |
β tags match by name β applied, source form restored |
Name: ACME Ltd. (tags dropped) |
β rejected, source kept, skipped_invalid +1 |
Name: </span><span>ACME (reordered) |
β rejected |
Opt out any time: ExtractionOptions::builder().inline_placeholders(false)
or the CLI flag --no-inline restores classic per-segment extraction.
| Format | Translatable elements | Inline elements | Translatable attributes |
|---|---|---|---|
| MJML | mj-title, mj-text, mj-button, strong, em |
strong, em |
β |
| HTML | p, h1βh6, span, div, a, button, label, li, td, th, title, option, strong, em, b, i |
the HTML phrasing set (a, abbr, b, br, em, i, kbd, mark, q, small, span, strong, sub, sup, time, u, var, β¦) |
alt, title, placeholder, aria-label |
| XML | everything (generic fallback) | β (opt in via a custom strategy) | β |
Note
Smart filtering β the extraction engine automatically excludes URLs,
e-mail addresses, file paths, lone entities ( ), hex colors,
pure numbers/symbols and placeholder-only strings (%s, {{name}}).
Custom formats: implement ExtractionStrategy β
is_translatable_element, is_ignored_element,
translatable_attributes and (new in 0.3) is_inline_element β and
pass it to extract_messages / apply_translations.
extract --merge (or the update subcommand) implements gettext
msgmerge semantics:
- strings still present keep their translation, flags, comments and plural forms;
- strings removed from the sources become
#~obsolete entries; - strings that come back are resurrected with their old translation;
- fuzzy translations are kept but skipped during compilation unless
--use-fuzzy(orPoCatalog::translations_with(true)) is set.
- name: Check translations
run: |
xml2po update src/templates/*.html --output locales/messages.po
xml2po check --min-coverage 90 locales/messages.po src/templates/*.htmlcheckexits0only when the catalog is in sync and coverage is at or above--min-coverage.check --jsonprints{"clean":true,"coverage":95.0,"added":[],"removed":[]}.stats --jsonprints{"total":42,"translated":40,"untranslated":2,"coverage":95.2}.--recursive --exclude 'drafts/*'extracts whole directory trees with glob exclusions.
Tip
WebAssembly usage β compile to wasm32-unknown-unknown and call
extract_to_po / compile_with_po from JavaScript via wasm-bindgen:
const po = extractToPo(mjmlContent, "mjml", "template.mjml");
const translated = compileWithPo(htmlContent, po, "html");| Feature | Description | Default |
|---|---|---|
mjml |
MJML format extraction and compilation | β |
html |
HTML format extraction and compilation | β |
xml |
Generic XML fallback strategy | β |
chrono |
Timestamps in generated PO headers | β |
serde |
Serialize/Deserialize for messages, options and catalogs |
β |
xliff |
XLIFF 1.2 export/import | β |
cli |
The command-line interface binary | β |
parallel |
Rayon-parallel extraction of multiple input files | β |
cli-encoding |
UTF-16 (BOM) input support in the CLI | β |
| PO construct | Extract | Parse | Serialize | Compile |
|---|---|---|---|---|
msgctxt |
β (opt-in) | β | β | β |
msgid_plural + msgstr[N] |
β | β | β | msgstr[0] |
#: references (file:line) |
β | β | β | β |
#, flags |
β | β | β | fuzzy policy |
| `# | ` previous msgids | β | β | β |
#~ obsolete entries |
β (merge) | β | β | skipped |
| Header metadata | β | β
(PoMetadata) |
β | β |
Wrapping at 79 cols / --no-wrap |
β | β | β | β |
# Run the test suite (unit + CLI integration + doc tests)
cargo test --all-features
# Lint with the pedantic configuration used by CI (warnings are errors)
cargo clippy --all-features --all-targets -- -W clippy::pedantic --deny warnings
# Check formatting
cargo fmt --all -- --check
# Test WebAssembly build
rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown
# Measure coverage (requires cargo-llvm-cov)
cargo llvm-cov --all-featuresA runnable library example lives in examples/translate_flow.rs:
cargo run --example translate_flow.
Important
When contributing a new format, implement the
ExtractionStrategy trait (elements, ignored
elements, translatable attributes, inline elements) and add a variant
to Format. Refer to the built-in strategies for the pattern.
MIT β see LICENSE.