Skip to main content

XML Tags

XML Tags are the foundation of XML because they define the scope of an element in XML.

Furthermore, they can also be used to insert comments, declare settings needed for environment analysis, and to insert special instructions.

What are Tags and Elements?

It's helpful to distinguish between a "tag" and an "element."

  • A Tag is the markup syntax itself, enclosed in angle brackets (e.g., <name> or </name>).
  • An Element is the complete component, consisting of a start-tag, its content, and an end-tag.

Example of an Element:

<name>Tom Nolan</name>
  • <name> is the start-tag.
  • Tom Nolan is the content.
  • </name> is the end-tag.

Classification of XML Tags

We can classify XML tags as follows:

Start Tags

A start-tag marks the beginning of an element. It consists of the element's name enclosed in angle brackets.

<name>

End Tags

An end-tag marks the end of an element. It is identical to the start-tag, but it includes a forward slash (/) before the element name.

</name>
note
  • The end tag includes a / before the name of the element!
  • Every element that has a start tag should end with an end tag.

Empty Tags

An element that has no content is called an empty element. This can be represented in two ways:

1. A Start-Tag Immediately Followed by an End-Tag:

<img></img>

2. A Self-Closing Tag (Recommended): A more concise and common way to represent an empty element is with a single "self-closing" tag, which includes a forward slash before the closing angle bracket.

<img/>
note

This is the recommended best practice for empty elements, and it is commonly used for elements that hold all their information in attributes, such as an image tag:

<img src="photo.jpg" alt="A photo"/>

XML Tags Rules

For an XML document to be "well-formed" and valid, each XML tag must follow these rules without exception.

Rule 2: XML Tags order must be respected

Rule 1: All Elements Must Have a Closing Tag

This is the most important rule. Every element you open must be closed. Unlike older versions of HTML, there are no "optional" closing tags in XML.

Rule 2: XML Tags are Case-Sensitive

The name of an element in the start-tag and the end-tag must have the exact same case.

  • <name> and <Name> are treated as two different tags.
  • <name>Tom</Name> is an invalid pairing and will cause a parsing error.
  • <name>Tom</name> is valid.

Rule 3: XML Elements Must Be Properly Nested

Elements must be closed in the reverse order in which they were opened. You cannot "overlap" tags.

  • Correct Nesting: <b><i>This is bold and italic.</i></b>
  • Incorrect Nesting: <b><i>This is invalid.</b></i> (The <i> tag must be closed before the <b> tag).

Another example:

<outer_element>  
<internal_element>
This tag is closed before the outer_element
</internal_element>
</outer_element>