XML | Attributes
Prerequisite: XML | Basics
The XML attribute is a part of an XML element. The addition of attribute in XML element gives more precise properties of the element i.e, it enhances the properties of the XML element.
<element_name attribute1 attribute2 ... > Contents... </element_name>
In the above syntax element_name is the name of an element which can be any name. The attribute1, attribute2, … is XML attribute having unique attribute name. Then in the content section, any message can be written and at the end, the element name is ended.
Below some examples are given which illustrate the above syntax:
In the above example, XML element is text, the category is the attribute name and message is the attribute value, Attribute name and its value always appear in pair. The attribute name is used without any quotation but attribute value is used in single ( ‘ ‘ ) or double quotation ( ” ” ).
In the above example, two attribute is used with different name. So, in a single element multiple attribute is used having unique attribute name.
But if we use two distinct element then we can use the attribute having the same attribute name. This can be understood with the help of below example:
There are three types of attributes discribed below:
- String types Attribute: This type of attribute takes any string literal as a value.
- Enumerated Type Attribute: This attribute is further distributed in two types-
- Notation Type: This attribute is used to declares that an element will be referenced to a notation which is declared somewhere else in the XML document.
- Enumeration: This attribute is used to specify a particular list of values which match with attribute values.
- Tokenized Type Attribute: This attribute is further distributed in many types:
- ID: This attribute is used to identify the element.
- IDREF: This attribute is used to refer an ID which has already been named for another element.
- IDREFS: This attribute is used to refer all IDs of an element.
- ENTITY: This attribute is used to indicate the attribute which will represent an external entity used in the document.
- ENTITIES: This attribute is used to indicate the attribute which will represent external entities used in the document.
Rules for creating an attribute: There are some rules that should be followed while creating an attribute:
- An attribute should not repeat itself in a single start or empty-element tag.
- An attribute should be declared using the attribute-list declaration in the DTD (Document Type Definition).
- An attribute element is used without any quotation and the attribute value is used in a single (‘ ‘) or double quotation (” “).
- An attribute name and its value should always appear in pair.
- An attribute value should not contain direct or indirect entity references to external entities.