elefcode
← All guides

Web & APIs · 4 min read

XML Explained: Elements, Attributes, and Namespaces

JSON took over web APIs, but XML is far from gone. It powers RSS feeds, sitemaps, SVG, Office documents, Android layouts, SOAP services, and countless enterprise integrations. Knowing its rules makes those files much less intimidating.

Try it yourself with the related tool.

Format and validate XML →

Advertisement

The strict syntax rules

XML is unforgiving where HTML is lenient. There must be exactly one root element, every tag must be closed (or self-closed like <br/>), tags must nest properly, attribute values must be quoted, and names are case-sensitive. A single mistake makes the whole document invalid, and parsers stop at the first error.

Five characters must be escaped in text: &lt;, &gt;, &amp;, &quot;, and &apos;. A <![CDATA[ ... ]]> section lets you include text without escaping.

Elements or attributes?

A common rule of thumb: use attributes for metadata about a thing (an id, a unit, a language) and child elements for the data itself, especially anything that might repeat or need structure. Attributes cannot contain nested markup and appear at most once each per element.

Namespaces

Namespaces stop names from different vocabularies colliding. xmlns:media="http://search.yahoo.com/mrss/" declares a prefix, and <media:content> then belongs to that vocabulary. The URL is just a unique identifier — nothing is fetched from it. Namespaces are why SVG and RSS files often start with several xmlns declarations.

XML vs JSON

JSON is smaller and maps directly onto programming-language objects, which is why APIs prefer it. XML is stronger for documents with mixed text and markup, and it has mature tooling for schemas (XSD), queries (XPath), and transformations (XSLT). Choose based on what the other side expects.

Related guides