The Attributes of an XML Element
An attribute is a value that is created as part of an element, making that value different from the value of a regular element. There are similarities and differences between an element and an attribute.
The element and the attribute have these in common:
The differences between an element and an attribute are:
Imagine you have an ISBN element as a child of a Video element as follows:
<video> <ISBN>0-7888-1623-3</ISBN> </video>
An attribute must be created inside the start-tag of an element. To create an attribute, type the left angle bracket of the element, followed by the name of the element, an empty space, and the name of the attribute. The name follows the same rules we defined for names in XML.
An attribute should have a value that can be used to distinguish it. To specify the name of an attribute, assign a value as a string to its name. In the case of the above code fragment, since ISBN is simply a child of the video element, you can change the ISBN element to become an attribute of the video element as follows:
ISBN is an attribute of the video element.
An element can have 0, one, or more attributes. While a certain element may have an attribute, a sibling element with the same name may not have an attribute or may have a completely different type of attribute. Here is an XML file with attributes in some elements:
<?xml version="1.0" encoding="utf-8" ?> <videos> <video ISBN="0-7888-1623-3"> <title Screenplay="Marty Kaplan">The Distinguished Gentleman</title> <director>Jonathan Lynn</director> <length>112 Minutes</length> <format>DVD</format> <rating>R</rating> </video> <video> <title WrittenBy="Charlie Peter">Her Alibi</title> <director>Bruce Beresford</director> <length>94 Mins</length> <format>DVD</format> <rating>PG-13</rating> </video> </videos>
Remember that you can include white spaces to make your code easy to read. This means that you can type an attribute on the next line of its element's name. In Lesson 1, we saw that every element must be closed. We saw that we could close an element with an end-tag as follows:
We also saw that we could close an element locally as follows: <video />. If you create an attribute in an empty element, you can also close it by typing the indicative forward slash before the right angle bracket and after an empty space. Here is an example:
<video ISBN="0-7888-1623-3" />
As mentioned already, an attribute primarily belongs to an element. This means that, when creating an attribute, you must specify what element it would belong to.
If an element has an attribute you don't want or that you don't need anymore, you can delete that attribute. To delete an attribute, simply click (place the caret) inside the element's tag and use the Delete or Backspace keys to remove the attribute and its value.