XML Elements vs. Attributes

For the attributes and the child elements in XML, there are no rules about when to use which one.

Use of Elements vs Attributes:

We can store the data either in child elements or in attributes.

Example 1:


  Tom
  Gates

Example 2:


  male
  Tom
  Gates

Explanation:

In the above examples, gender is an attribute in the first one and a child element in the second one, however providing the same information.

Recommended Way:

We can use either of the attributes or child elements. The attributes can be handy in HTML. In XML, however, we should try to avoid them, and if the information feels like data, we can use the child elements. What we recommend is that the data itself should be stored as elements, and only the metadata, i.e., the data about data should be stored as attributes.

Example 1:


  Sapna
  Tom
  Message
  Meeting on Monday at 11 AM.

Example 2:


  1/8/2020
  Sapna
  Tom
  Message
  Meeting on Monday at 11 AM.

Example 3: RECOMMENDED WAY:


  
    1
    8
    2020
  
 Sapna
  Tom
  Message
  Meeting on Monday at 11 AM.

Explanation:

In the above examples, all three XML documents contain the same information. However, a date attribute is used in the first example, a date element is used in the second example and an expanded date element is used in the third example.

Why to avoid using attributes?

Some of the limitations of attributes are:

  • They cannot contain multiple values, but the child elements can.
  • They are not easily expandable for future changes.
  • They cannot describe structures, but the child elements can.
  • They are more difficult to manipulate by program code than the child elements.
  • Their values are not easy to test against a DTD.

Using attributes as containers for data results in a document that is difficult to read and maintain. It is recommended to use the child elements to describe data, and the attributes to provide information that is not relevant to the data.

Incorrect Way:

XML should not be used like this:



Exception:

The ID references can be assigned to the elements, and can then be used to access the XML elements in much the same way as the NAME or ID attributes in HTML.

Example:



  Sapna
  Tom
  Message
  Meeting on Monday at 11 AM.



  Tom
  Sapna
  Re: Message
  Thanks for the reminder!


Explanation:

In the above example, ID is used as a counter, or a unique identifier, to identify the different notes in the XML file. Here, the ID is not a part of the note data.