Concepts / Well-Formed and Valid XML Documents

Well-Formed and Valid XML Documents

A well-formed XML document follows a strict syntax, and a single violation is enough to make the whole document unusable for a reader that expects those rules.

  • Programming

Why One Stray Character Breaks a File

Suppose you are handed a list of books written in XML. The indentation is tidy, the names are meaningful, and most tags close where you expect them to. The file looks almost right. Yet one stray capital letter or one missing pair of quotation marks can make the entire file unusable for a program that reads it.

XML is unforgiving in exactly this way, and that is by design. A program reading XML does not guess what you meant. It checks the text against a fixed set of syntax rules, and a document that passes those checks is called well-formed. In this article you will learn those rules, see how they fail together in a single fragment, and practice repairing one.

Counting the Errors in a Broken Fragment

Before looking at the rules one by one, it helps to see them fail together. The fragment below describes a shelf containing one book. Read it once and try to count how many things are wrong with it before you read on.

xml

What do you think happens?

How many separate things are wrong with this fragment?

  • One

  • Two

  • Three

  • Four

Reveal answer
Answer:

Four

The title attribute opens with a single quote but closes with a double quote, so its value is never properly enclosed. The Title start tag is capitalized, but its end tag is lowercase, and tag names are case sensitive, so they do not match. The sku element is still open when book closes, so the tags cross instead of nesting. The ampersand in 10 & up begins a reference that is not a valid entity, so it is read as markup rather than plain data.

The Shape Rules: Closing Tags and Nesting

Every tag in a well-formed document is either empty, written as a single self-closing tag, or it has an end tag that matches it. The word matching carries a precise meaning. If one element sits inside another, its end tag must also sit inside that same outer element. Elements may contain other elements, but they may not overlap.

Overlapping tags are the classic sign that nesting has broken down. Think of each element as a box that must fit entirely inside its parent box. When an inner box starts inside the parent and ends after the parent has already closed, the boxes cross, and no tree can describe that arrangement. The repair is to close the innermost element first and work outward.

A well-formed document also needs a single root element, the outermost element that contains everything else. Every other element must live somewhere beneath that root. The diagram below shows the shelf document as a tree. Each box is an element, and each line means contains.

shelfbookTitleskupricecontainscontainscontainscontains
Which element contains which, and why must the sku tag close inside book rather than after it?

In the tree, the root shelf sits at the top and every other element lives somewhere beneath it. The sku element is a child of book, so its end tag must appear before the end tag of book. In the broken fragment the end tag </book> appeared while sku was still open, which is the crossing the rules forbid.

Naming Tags and Attributes

XML gives its author a lot of freedom in naming. The names you invent for tags and attributes are not fixed by the language itself, and a good name tells a human reader what the data means. A name like price is far more useful than a vague label like p1. The freedom has limits, and those limits concern what a legal name looks like and how names are compared.

Key point

Tag names and attribute names are case sensitive, must start with a letter, and should be chosen to describe the data clearly for a human reader. Title and title are two different names, so a start tag and an end tag must use exactly the same capitalization.

Candidate nameValid?Reason
priceYesStarts with a letter and describes the data
PriceYesLegal, but differs from price in case
p1YesLegal, but tells a human reader little
1priceNoDoes not start with a letter
unit priceNoContains a space

Checking candidate names against the naming rules

Quoting Attribute Values

An attribute attaches a piece of information to an element through a name and a value. In XML the value is not optional. Every attribute needs one, and that value must be wrapped in quotation marks. Either a pair of single quotes or a pair of double quotes will do, as long as the same kind opens and closes the value. Mixing them is an error.

xml

The first two lines are well-formed, using single quotes and double quotes respectively. The third line opens the id value with a double quote and closes it with a single quote, so the value is never properly enclosed. Choose one quote style for a document, or at least keep it consistent within each attribute.

Escaping the Less-Than Sign and Ampersand

Two characters have special jobs in XML. The less-than sign opens a tag, and the ampersand begins a reference. If either one appears inside attribute values or ordinary text, the parser could mistake it for markup. To use these characters as plain data, you write an entity in their place. An entity is a named reference that stands for a single character.

xml

Reading this line, the text content is Price, a less-than sign, the number 10, an ampersand, and the words in stock. The entities are what allow those two dangerous characters to survive inside the text. The diagram below breaks the text node into its pieces.

Priceplain text&lt;stands for less-than sign10plain text&amp;stands for ampersandin stockplain text
How does a parser read the escaped text inside price, and what data does it store?

Repairing the Fragment Step by Step

Now apply the rules to the fragment you counted earlier. Work through the violations in the order they appear, changing one thing at a time, and check each change against the rule it serves.

Before
<shelf>
  <book id="b1" title='Dune">
    <Title>Dune</Title>
    <sku>BK-101</book>
    <price>10 & up</price>
  </sku>
</shelf>

Four violations: mismatched quotes, mismatched case, crossed tags, bare ampersand

After
<shelf>
  <book id="b1" title="Dune">
    <title>Dune</title>
    <sku>BK-101</sku>
    <price>10 &amp; up</price>
  </book>
</shelf>

Well-formed: matching quotes, matching case, nested tags, escaped ampersand

Worked example

Tracing each violation to its fix

Repair the broken shelf fragment so that a strict parser accepts it as well-formed.

  1. 1
    Fix the quotes

    The title value opened with a single quote and closed with a double quote. Changing the opening quote to a double quote makes the pair match.

  2. 2
    Fix the case

    The start tag Title and end tag title differ in capitalization. Because names are case sensitive, one of them must change. Lowercase title is the consistent choice.

  3. 3
    Fix the nesting

    The sku element was open when book closed. Closing sku first with the correct end tag, and then closing book, makes the elements nest.

  4. 4
    Escape the ampersand

    The bare ampersand in 10 & up begins a reference that does not form a valid entity. Writing it as the ampersand entity lets the text survive as plain data.

Result

Every start tag now has a matching end tag in the right order, every attribute value is enclosed in matching quotes, and the text is safe to read.

Mistakes Beginners Make with XML Syntax

  • Common mistake

    Assuming indentation makes the nesting correct

    What it looks like

    Tags that are neatly indented but cross each other, such as a book closing before its sku child.

    Why it fails

    Indentation is for human readers. The parser checks the actual start and end tags, not the spacing before them.

    Do this instead

    Check that each end tag closes the most recently opened element that is still open.

  • Common mistake

    Treating Title and title as the same name

    What it looks like

    Opening with Title and closing with title.

    Why it fails

    Tag names are case sensitive, so the two spellings name different things and the element never closes.

    Do this instead

    Use exactly the same capitalization in the start tag and the end tag.

  • Common mistake

    Mixing quote styles within one attribute

    What it looks like
    title='Dune" with a single quote opening and a double quote closing.
    Why it fails

    The value is never properly enclosed, so the attribute is malformed.

    Do this instead

    Close the value with the same quotation mark that opened it.

  • Common mistake

    Writing a bare ampersand or less-than sign in text

    What it looks like

    price 10 & up, or a comparison such as price < 10 written directly inside an element.

    Why it fails

    The parser reads these characters as the start of markup or a reference.

    Do this instead

    Write the entity instead, for example &amp; or &lt;.

  • Common mistake

    Leaving an attribute without a value

Edge case

A single violation is enough to make the whole document unusable for a reader that expects these rules. The fragment may have only one broken quote among dozens of correct lines, and a strict parser still rejects the entire file. Processing does not skip the bad line and carry on.

Well-Formed Versus Valid

Well-formedness is the first layer of rules. It asks whether the text follows XML syntax at all: matching tags, nesting, one root, quoted attributes, and escaped reserved characters. A document that passes these checks is well-formed. Validity is a second layer, a set of additional constraints that the content must satisfy in order to count as valid. The source material for this article concentrates on the syntax layer, so the discussion here is limited to that distinction.

Matching end tagsContent constraintsOne root elementQuoted attributevaluesmust hold before validity is checked
How do the syntax rules of the well-formed layer differ from the constraint rules of the valid layer?
Key point

Check well-formedness first. A document that is not well-formed cannot be meaningfully checked against further constraints, because the parser cannot even establish its structure.

Practice: Find the Violation

MEDIUM

The fragment below contains a single rule violation. Identify the line, name the rule it breaks, and write the corrected line.

<order><item sku="A7"><qty>2</qty></item><note>Gift wrap & card</Note></order>

Hints
  • Compare each start tag with its end tag, including capitalization.
  • Look at the text inside note for any character that might begin markup.

Key Takeaways

  • A well-formed XML document follows strict syntax rules, and a single violation makes the whole document unusable for a strict reader.
  • Every element must be empty or have a matching end tag, elements must nest without overlapping, and the document needs a single root element containing all the others.
  • Tag and attribute names are case sensitive, must start with a letter, and should describe the data clearly; every attribute value must be enclosed in matching single or double quotes.
  • The less-than sign and ampersand must be written as the entities &lt; and &amp; when they appear as plain data inside text or attribute values.
  • Well-formedness is the syntax layer and comes first; validity adds further constraints on top of it.