Elements are used to categorize the data in XML document, thus making the data “self-explanatory”. A tag is just another name for an element. An opening tag is the element name enclosed in brackets and a closing tag is the same as an opening tag with a slash before the element name. The information of the elements is enclosed within open and closing tags. An example of this is shown below:
Attributes are used provide more specific information about the element and appear within the opening tag. Attributes provide a way to focus elements in a way to fit the needs of the XML document creator. If there are several values possible for an attribute, the value must be specified. So if a tag has an attribute for color the values may be green, yellow, blue, red, etc. An example of an element attribute is the following:
Example: <animal breed=Siamese>cat</animal>
There are some rules to consider when determining element names. They are the following:
- cannot contain spaces
- can contain letters, numbers, and any other characters
- cannot begin with a number or a punctuation character
- cannot begin with “xml”
With these rules in mind, there are also some best practices associated with element naming. They include the following:
- Since some XML documents have a corresponding database it is a good idea to use the naming rules of that database.
- Non-English letters are acceptable in XML, but be sure that the software being used supports them.
- Make names as descriptive as possible.
- Don’t hesitate to use an underscore as a separator: <first_letter>, <last_letter>.
- Try to keep names short and simple. For example, Use <baby_name> rather than <the_name_of_the_baby>.
- Avoid the “.” character. For example, in “first.letter,” some software may interpret this to mean that “letter” is a property of the object “first.”
- Avoid the “-” character. For example, in “first-letter,” some software may interpret this to mean that you want to subtract “letter” from “first”.
- Avoid the “:” character because colons are usually reserved for namespaces.