XML Attributes

Similar to HTML, XML elements can have attributes that are designed to contain data related to a specific element.

XML Attributes Must be Quoted:

Being always quoted, the attribute values can have either single or double-quotes.

For example:

<student gender="male">

or like this:

<student gender='male'>

If the double quotes are already present in the attribute value itself then we can use single quotes.

For example:

<student name='Tom "James" Smith'>

or we can also use character entities to serve the same purpose:

<student name="Tom &quot;James&quot; Smith">

XML Elements vs. Attributes:

Example 1:

<student gender="male">
  <firstname>Tom</firstname>
  <lastname>Smith</lastname>
</student>

Example 2:

<student>
  <gender>male</gender>
  <firstname>Tom</firstname>
  <lastname>Smith</lastname>
</student>

Explanation:

In the above examples, gender is an attribute in the first example and is an element in the second example. However, both have the same information. We can use either of the attributes or elements in XML.

The below three XML documents have the same information:

Example 1:

<note date="2020-06-04">
  <to>Sapna</to>
  <from>Tom</from>
</note>

Example 2:

<note>
  <date>2020-06-04</date>
  <to>Sapna</to>
  <from>Tom</from>
</note>

Explanation:

In the above example, we used a <date> element.

Example 3:

<note>
  <date>
    <year>2020</year>
    <month>06</month>
    <day>04</day>
  </date>
  <to>Sapna</to>
  <from>Tom</from>
</note>

Explanation:

In the above example, we used an expanded <date> element.

Things to consider while using XML attributes:

  • XML attributes cannot contain multiple values, but XML elements can.
  • XML attributes cannot contain tree structures, but XML elements can.
  • XML attributes are not easily expandable.

XML Attributes for Metadata:

The ID references assigned to the elements are used to identify XML elements. It is similar to the id attribute in HTML. For identifying the different notes, we use the id attributes, but they are not a part of the note itself. The metadata i.e., the data about data is to be stored as attributes. However, the data itself should be stored as elements.

Example:

<messages>
  <note id="100">
    <to>Sapna</to>
    <from>Tom</from>
    <heading>Meeting</heading>
    <body>Monday at 11 AM!</body>
  </note>
  <note id="200">
     <to>Sapna</to>
    <from>Tom</from>
    <heading>Re: Meeting</heading>
    <body>Thanks for the reminder!</body>    
  </note>
</messages>
Please Share