Free, independent guides since 2010

Code

XML basics: elements, attributes and well-formed documents

A beginner’s introduction to XML: elements and attributes, the XML declaration, well-formedness rules, namespaces, entities and CDATA, and where XML is used on the web.

<guide section="Code" type="guide" read="1 min"/>

XML (Extensible Markup Language) has been around since 1998 and is still everywhere: in the XML sitemap that tells search engines about your pages, in RSS feeds, in SVG images and in many business systems. Before you start processing it with dom4j, it helps to know the rules.

A first XML document

XML
<?xml version="1.0" encoding="UTF-8"?>
<!-- A small product catalogue -->
<catalogue shop="Spaak">
  <product id="p1" stock="12">
    <name>Inner tube 28"</name>
    <price currency="EUR">6.50</price>
  </product>
</catalogue>

The rules of well-formed XML

  1. Exactly one root element (here catalogue).
  2. Every opening tag has a closing tag, or is self-closing: <br/>.
  3. Tags are properly nested: no <a><b></a></b>.
  4. Names are case-sensitive: <Name> is not <name>.
  5. Attribute values are always in quotes.
  6. Special characters are escaped: &lt;, &amp;.

Elements or attributes?

A common convention: use attributes for metadata about an element (ids, units, flags) and elements for the actual data, especially when it can contain text or structure.

Namespaces

XML
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
  <url>
    <loc>https://dom4j.org/</loc>
    <image:image><image:loc>https://dom4j.org/og-dom4j.png</image:loc></image:image>
  </url>
</urlset>

Namespaces let vocabularies from different sources live in one document without name clashes – this is a real excerpt of how our own sitemap works. Querying namespaced XML is explained in XPath with dom4j.

CDATA and entities

A CDATA section contains text that should not be parsed as markup, such as HTML snippets. Entities are named references; be careful with external entities, which are a security risk (see secure XML parsing).

Comparing formats? Read JSON and XML compared.

Frequently asked questions

What is the difference between HTML and XML?

HTML has a fixed set of tags for web pages and browsers are forgiving with errors. XML lets you define your own tags for any data and is strict: a single error makes the document invalid.

What does well-formed mean?

The document follows XML’s syntax rules. A valid document is well-formed and also follows a specific schema or DTD.