Skip to main content

XML Elements

An XML element is anything delimited by start and end tags or an empty-element tag in the case of empty elements.

An element can contain:

  • text
  • attributes
  • other elements
  • or a mix of the above
note

Each XML document contains one or more elements.

Syntax

The syntax is as follows:

<element-name attribute1 attribute2> 
....content
</element-name>

where:

  • element-name is the name of the element.
  • attribute1, attribute2 are attributes of the element separated by white spaces. Each attribute defines a property of the element and it is written as name="value" where value is a string inside single '' or double "" quotes.

Syntax for Empty Element

The syntax of an element with no content (empty element) is as follows:

<element-name attribute1 attribute2.../>
note

Empty elements can have attributes.

Example

Example with some XML elements:

<?xml version = "1.0"?>
<contact-info>
<address category="residence">
<name>Tom Nolan</name>
<company>ACME Inc.</company>
<phone>(123) 456-6789</phone>
</address>
</contact-info>

XML Elements Rules

XML elements must follow these rules:

  • Element names are case-sensitive. For example, name, Name, NAME are different names.
  • Element names must start with a letter or underscore
  • Element names can't start with the letters xml (or XML, or Xml, etc.)
  • Element names can contain letters, digits, hyphens (-), underscores (_) and periods
  • Element names cannot contain spaces
  • An element, which is a container, can contain text or elements

Naming Style

There aren't naming styles defined for XML elements. But These are some commonly used:

StyleExampleDescription
Lower case<firstname>All letters lower case
Upper case<FIRSTNAME>All letters upper case
Underscore<first_name>Underscore separates words
Pascal case<FirstName>Uppercase first letter in each word
Camel case<firstName>Uppercase first letter in each word except the first
note

It's important to be consistent with the style you choose!