Back to Guides

XML and TEI for annotated texts

Record annotation inside a text with XML and TEI, and let an agent generate what you read from it.

Many researchers work with texts where the words alone are not enough. For example, editions that record where two versions of a text disagree, or a corpus for linguistic investigation where every word is tagged with one or more grammatical categories.

When an archive needs such detailed annotation, it is best served by a more complex format such as XML or TEI, a vocabulary written in XML that is used in the digital humanities. However, as the level of detail increases, these documents become completely unreadable by humans. With an AI agent such as Claude Code or Codex, you no longer have to read or write the XML yourself. The agent keeps the XML as the record, checks it after every change, and generates from it what you read and what you compute on.

Each step has its own guide in this series - co-written with my agents based on the work they did for me. To make it simple, I use first person throughout:

  1. Publishing research results with Cloudflare: putting a folder of files online at a public address.
  2. Building research sites from data files: Astro and fast search: turning data files into a site people can search.
  3. Git and GitHub for sharing data with agents (coming soon): keeping the files where collaborators and their agents can work on them.
  4. Spreadsheets and tabular data with agents: turning workbooks into tables an agent can maintain.
  5. From a pile of mixed documents to an agent-friendly knowledge repository: turning documents into a repository an agent can maintain.
  6. Data formats for working with agents: an overview: which format to keep research data in.
  7. Markdown and YAML: a primer for working with agents: how to read and write the two formats most of this series uses.
  8. XML and TEI for annotated texts (this guide): recording annotation inside a text and generating what you read from it.

When headings and fields are not enough: annotation inside the text

In the rest of this series, the structure of a record sits around the text: headings in Markdown, and fields such as date and status in a YAML block at the top of the file. That stops working when what you need to record belongs to particular words inside a sentence: this word is a person's name, this one is a place, here one version of the text reads differently from another.

Start with a conversation about what you need to distinguish

Before asking an agent to annotate or convert anything, start a conversation with it about the text and what your research needs to tell apart:

  • what the text is and where it comes from: a printed book, a manuscript, several typescripts, transcribed speech;
  • what you need to mark inside it: names, places, titles, differences between versions, the grammatical category of each word;
  • what questions the annotation should help you answer;
  • whether your field already has an established schema for this kind of material.

Then ask the agent to propose the smallest set of markup that records those distinctions, and to write the choice down in the repository.

A Czech passage, first as text and then with names marked

Let's use a short fictional passage in Czech throughout this guide. This is how a reader sees it:

Když Anna vystoupila na nádraží v Brně, pršelo. V hale voněla káva. Vytáhla z batohu Staré pověsti české, ale než dočetla stránku, z reproduktoru se ozvalo její jméno.

In English: When Anna got off at the station in Brno, it was raining. The station hall smelled of coffee. She took Old Czech Legends out of her rucksack, but before she had finished a page, her name was called over the loudspeaker.

Here is the same passage with the entities: the person, the place and the book title marked:

<p>
  Když <persName>Anna</persName> vystoupila na nádraží v
  <placeName>Brně</placeName>, pršelo.
  V hale voněla káva. Vytáhla z batohu
  <title>Staré pověsti české</title>, ale než dočetla stránku,
  z reproduktoru se ozvalo její jméno.
</p>

This is still readable. Each label sits around the words it describes, and the sentence stays in reading order. A script can now list every person, place and title across a thousand such files. But the text says Brně, the form of Brno used after v (in). A linguist wants to record that Brně is a form of Brno, and what kind of word each of the others is. That takes annotation of every word.

XML in five minutes

XML (Extensible Markup Language) is a way of writing labels into text (XML specification). These are the terms you need:

  • An element is a labelled piece of the document. <placeName>Brně</placeName> is one element.
  • A tag marks where an element starts and ends: <placeName> is the start tag and </placeName> the end tag. An element with nothing inside can be a single tag, such as <anchor/>.
  • An attribute is a named value inside the start tag. In <w lemma="Brno">Brně</w>, lemma is an attribute and Brno its value.
  • Nesting means elements sit inside other elements, and each must close before the element around it closes. A placeName can sit inside a p; it cannot start inside the p and end after it. An XML document is therefore a tree.
  • A document is well formed when it follows these writing rules: every start tag has its end tag, elements nest properly, attribute values are in quotes. Any XML parser (a program that reads XML) checks this.
  • A schema is a set of rules for one kind of document: which elements are allowed, where, and with which attributes and values. A document is valid when it is well formed and follows its schema. TEI schemas are usually written in RELAX NG. Rules about how parts relate, such as "every witness a reading points to must be listed", can be written in Schematron.

Where it becomes unreadable

Now add the grammar. Here is the first sentence with each word in a w (word) element carrying its lemma (the dictionary form) and its part of speech, and each punctuation mark in a pc element:

<s xml:id="p1-s1">
  <w lemma="když" pos="SCONJ">Když</w>
  <persName><w lemma="Anna" pos="PROPN">Anna</w></persName>
  <w lemma="vystoupit" pos="VERB">vystoupila</w>
  <w lemma="na" pos="ADP">na</w>
  <w lemma="nádraží" pos="NOUN">nádraží</w>
  <w lemma="v" pos="ADP">v</w>
  <placeName><w lemma="Brno" pos="PROPN">Brně</w></placeName>
  <pc pos="PUNCT">,</pc>
  <w lemma="pršet" pos="VERB">pršelo</w>
  <pc pos="PUNCT">.</pc>
</s>

The part-of-speech labels are illustrative and follow the Universal Dependencies tagset: SCONJ is a subordinating conjunction, PROPN a proper noun, ADP a preposition. Nine words now take twelve lines, and you can no longer read the sentence as Czech. A real corpus adds more: an identifier on every word, morphological features such as case and tense, and the syntactic relations between words. That is what I mean when I say that these documents become completely unreadable by humans. A parser reads them without difficulty, and so does an agent with a script.

TEI: a shared vocabulary written in XML

XML says only how labels are written. Anyone can invent <place>, <town> or <misto>. The Text Encoding Initiative (TEI) publishes Guidelines that fix which labels to use for texts and what each means: p for a paragraph, persName for a personal name, placeName for a place name, app for a place where versions differ. The current edition is TEI P5. A TEI file also has a header (teiHeader) that records the source, who is responsible for the encoding, the encoding policy and the revision history (TEI header).

The Guidelines are organised in modules, such as common elements, names and variants, and nobody uses all of them. A project writes down the modules and elements it uses in an ODD (One Document Does it all), a file that combines prose documentation with machine-readable rules, and generates its schema from it (ODD). Two files can both conform to TEI and record different things (conformance), so the ODD is where a reader finds out what yours records.

Some communities have already made this choice for their material:

  • TEI Lite is a general introductory selection of common TEI elements.
  • EpiDoc is a TEI customisation, with guidelines and tools, for editions of ancient documents such as inscriptions and papyri.
  • The DTA Base Format of the Deutsches Textarchiv fixes the choices for source description, transcription, typography and structure of historical German texts.

Linguistic annotation and corpora

For a corpus, the record and the format you analyse it in are usually different files. TEI keeps the text, its structure, its metadata and its annotations together. Most analysis tools want one word per line.

  • CoNLL-U, the format of Universal Dependencies, gives each token a line with ten tab-separated fields, including the word form, lemma, part of speech, morphological features and dependency relations. A manuscript description, uncertain readings or a speaker's history have no standard columns (CoNLL-U).
  • Vertical files also have one token per line, plus XML-like tags marking sentences or documents. Concordance tools such as the Corpus Workbench and Sketch Engine index them for searching by word patterns. The XML hierarchy, editorial detail and links can be left out.

ParlaMint, a collection of parliamentary debates with over 1.2 billion words from 29 countries and autonomous regions in release 5.0, works this way. It keeps TEI XML as the record, validated against schemas based on the Parla-CLARIN TEI recommendations, and derives CoNLL-U files, tables of speech metadata and vertical files for concordance tools from it (ParlaMint 5.0; schemas).

My English–Czech corpus

In the early 2000s I built a small parallel corpus of English and Czech texts and their translations. I wanted to investigate what happens to certain properties that are hard to study when you translate Czech into English and English into Czech. I was a translator for many years, and building the corpus by hand was hard work. Shortly before my talk at the Oxford Data Meetup in November 2026, I gave it to my agents. They rebuilt it, expanded it and annotated it again, and I am now finding things out that I could not afford to before.

Variants and editions

A witness is a source that attests a version of a text: a manuscript, a printed edition, a typescript. A reading is what one witness has at a given place. A critical apparatus records where the witnesses differ. In TEI, an app (apparatus entry) marks one place of variation, lem holds the lemma and each rdg holds a reading. In textual criticism the lemma is the base reading, a different sense from the dictionary form above. The wit attribute says which witness has the reading. The witnesses are listed once, in a listWit, each with an identifier called a siglum (critical apparatus, §13.1).

Suppose the Czech passage survives in two fictional typescripts, A and B. Where A has pršelo (it was raining), B has mrholilo (it was drizzling). Where A has ozvalo (was called), B has zaznělo (sounded). The witness list:

<listWit>
  <witness xml:id="A">Typescript A (fictional)</witness>
  <witness xml:id="B">Typescript B (fictional)</witness>
</listWit>

The paragraph with both variants:

<p xml:id="p1">
  Když <persName>Anna</persName> vystoupila na nádraží v
  <placeName>Brně</placeName>, <app>
    <lem wit="#A">pršelo</lem>
    <rdg wit="#B">mrholilo</rdg>
  </app>.
  V hale voněla káva. Vytáhla z batohu
  <title>Staré pověsti české</title>, ale než dočetla stránku,
  z reproduktoru se <app>
    <lem wit="#A">ozvalo</lem>
    <rdg wit="#B">zaznělo</rdg>
  </app> její jméno.
</p>

A full TEI file also has a header describing the source, and the witness list sits there, in the source description (sourceDesc).

TEI has three ways to attach a reading to the text, and the header's variantEncoding element records which one a file uses (critical apparatus, §13.2):

  • Parallel segmentation is the method above. The alternatives sit inline, so a reading text for A or for B is easy to generate. Variants can nest but cannot cross.
  • Location-referenced entries sit in a separate apparatus and point to a line or other numbered unit, which suits transcribing a printed apparatus. If the word occurs twice in that unit, the reference does not say which.
  • Double end-point attachment puts anchors at both ends of the exact span, and a separate apparatus entry points to them. Boundaries are exact and variants can overlap, at the cost of more identifiers and tools that follow them.

You do not read the XML

The agent keeps the XML. You read what it generates from it. For the Czech passage, a short script produces these three views.

The reading text of witness A:

Když Anna vystoupila na nádraží v Brně, pršelo. V hale voněla káva. Vytáhla z batohu Staré pověsti české, ale než dočetla stránku, z reproduktoru se ozvalo její jméno.

Choosing witness B gives the same text with mrholilo and zaznělo.

A table of variants:

Place in text Main reading Other reading Witness
p1, sentence 1 pršelo mrholilo B
p1, sentence 3 ozvalo zaznělo B

A table of words for the first sentence of witness A:

Word Lemma Part of speech
Když když SCONJ
Anna Anna PROPN
vystoupila vystoupit VERB
na na ADP
nádraží nádraží NOUN
v v ADP
Brně Brno PROPN
, , PUNCT
pršelo pršet VERB
. . PUNCT

Each view comes from a script kept in the repository, and the agent reruns it whenever the XML changes. Nobody edits the views by hand. A correction goes into the XML, and the views are generated again.

Projects have found other ways to spare people the raw XML, and each gives something up:

  • A lighter notation that converts to TEI. Papyri.info's editor, SoSOL, lets papyrologists write in Leiden+, close to conventions they already use, and converts it to EpiDoc. You get only the distinctions the notation covers.
  • A rendered view. CETEIcean displays TEI in a browser, and TEI Publisher produces reading, search and facsimile views. You see only what the view is configured to show.
  • Annotations kept beside plain text. In stand-off annotation, each annotation points to a position or a quotation in a clean text, as in the W3C Web Annotation model. Positions can move when the text is edited, and a repeated quotation can be ambiguous.

What the agent does

I don't write code by hand. Agents write it for me. In a TEI project, the agent writes the conversion scripts: from the XML to the reading text, the variant table, the word table, CoNLL-U or vertical files, and a website.

It also validates, at three levels, after every change, and reports the results:

  1. Parse: is the XML well formed?
  2. Schema: does it follow the schema generated from the project's ODD?
  3. Project rules: do the Schematron rules hold, for example that every wit points to a listed witness?

Validation cannot tell you whether the content is right. A valid file can assign a reading to the wrong witness, place an anchor a word too late, or leave out a distinction the schema makes optional (critical apparatus; Schematron). A wrong lemma passes just as easily. Those have to be checked against the source on a sample, and the agent should say which sample it checked.

Two studies I know of have tested language models on TEI work:

  • Causin and colleagues used models to add named-entity markup and Wikidata identifiers to 34 articles of an already encoded TEI corpus. Automated review found incorrect links among annotations marked high-confidence, and human review missed four out of five mismatches in the paper's sample. They also report three instances of malformed XML after model or human edits and name parsing as a missing check. The study covers enrichment of existing files, with no result about producing an edition from scratch (paper).
  • Ogawa's workshop abstract reports an exploratory test of three models (GPT-5, Gemini 2.5 Flash and Claude 4 Sonnet) converting Leiden-style transcriptions of nine inscriptions to EpiDoc. GPT-5 did best overall, and detailed examples in the prompt improved attribute matches. (abstract).

But models have progressed even more since these investigations and are now much more reliable. However, annotating extremely large corpora may be very expensive for now.

But where agents may still be costly for annotation of extremely large corpora, they are very cheap and effective when dealing with annotated documents and building tools for viewing them. When the mapping from TEI to a view is explicit, a script written on demand makes it practical to keep a rich record and generate whatever working format a task needs, and schema checks and known examples make that repeatable even when an agent drafted the script.

Size, speed and Git with large XML collections

The Helsinki Corpus TEI XML Edition is a 17 MB XML distribution, 4 MB compressed (Helsinki Corpus). The developers of ParlaMint report over 240 GB and almost 160,000 files for ParlaMint I in Git, and about four hours for the initial staging and commit. A change in automated annotation can touch nearly every file, so they kept small samples in GitHub and distributed the corpus through a corpus repository (TEI and Git in ParlaMint). These figures describe two projects. They do not measure XML speed in general.

Git shows changes line by line. With one element or sentence per line, an edit shows up as the line that changed; reformatting a whole file makes every line look changed (Git attributes).

Concordance indexes, search databases, word tables and vertical files are all generated from the XML by scripts, so they can be thrown away and rebuilt. A correction made only in one of them is not in the record, so the agent makes it in the XML and rebuilds.

Embeddings that point back to an exact passage and reading

An embedding is a list of numbers computed from a passage of text, so that passages with similar content get similar numbers. I call them semantic fingerprints. They are useful for finding similar passages, but they are secondary now that an agent can load 20 long documents and answer questions about them at once.

If you make embeddings from a TEI file, decide which text goes in. Stripping all the tags from the first sentence gives Když Anna vystoupila na nádraží v Brně, pršelo mrholilo, with both readings run together. So the agent extracts one reading at a time and stores with each vector the file, the element identifier, the version and the reading that was embedded: for example nadrazi.xml, element p1, version r3, witness B. A hit then points back to exact words in an exact version. Whether keeping some tags in the embedded text would help retrieval in TEI editions has not been tested in the sources I have (critical apparatus; xml:id).

When not to use it

If headings and YAML fields cover what your research distinguishes, stay with Markdown. Use TEI when you need to mark particular words inside the text, or when your field already shares a TEI schema for your material. Data formats for working with agents: an overview and Markdown and YAML: a primer for working with agents cover the simpler formats.

Give this guide to your agent

Copy this and give it to your agent (Claude Code, Codex or another). The agent can read the whole guide and the rest of the series on this site, each page also as a Markdown file written for agents.

Read https://semanticmachines.fyi/guides/xml-and-tei-for-annotated-texts (and https://semanticmachines.fyi/llms.txt for the rest of the series), then help me record and work with annotation in my texts the way it describes. Start by asking me what my research needs to distinguish in the text.

What your agent takes from this guide

This is the practice the guide describes, written for the agent. It is here so that you can see what your agent will work from.

# Practice: annotated texts in XML and TEI

Purpose: keep annotated texts as TEI XML, spare the user the raw XML, and
generate checked views from it by script.

## Ask first
- Ask what the text is, where it comes from, what the research needs to
  distinguish inside it (names, places, variants, word-level grammar) and
  what questions the annotation must answer.
- Ask whether a community schema exists for the material (EpiDoc, DTA Base
  Format, Parla-CLARIN, a project ODD). If one does, start from it.
- If headings and YAML fields cover the distinctions, recommend Markdown
  with YAML instead of TEI.

## The record
- Propose the smallest TEI subset that records the agreed distinctions.
  Write the choice in an ODD and in AGENTS.md.
- The TEI XML is the record. Give paragraphs, sentences, words, witnesses
  and anchors stable xml:id values. Never renumber them.
- List witnesses in a listWit in sourceDesc. Point every reading to its
  witness with wit. Record the attachment method in variantEncoding.
- Keep originals (scans, typescripts, source files) unchanged in sources/.
- Write one element or sentence per line. Do not reformat whole files.

## Views
- Never ask the user to read or hand-edit raw XML when a view can be
  generated.
- Generate the reading text for each witness, a variant table (place, main
  reading, other reading, witness) and a token table (word, lemma, part of
  speech) with scripts kept in the repository. Rerun them after every change.
- Never edit a generated view by hand. Correct the XML and rebuild.
  Indexes, CoNLL-U and vertical files are derived the same way.

## Checks
- After every change: parse for well-formedness, validate against the
  schema, run the project rules (Schematron). Report the results.
- Validation does not check content. Compare a sample against the source
  for wrong witnesses, misplaced anchors, missing distinctions and wrong
  lemmas. Say which sample you checked and what you found.

## Embeddings
- Embed one reading at a time. Stripping apparatus tags runs readings
  together.
- Store with each vector: file, element xml:id, version and which reading
  or witness was embedded.

Cite this page

Lukeš, Dominik (n.d.). XML and TEI for annotated texts · SemanticMachines. SemanticMachines. https://semanticmachines.fyi/guides/xml-and-tei-for-annotated-texts