Introduction to XML | XML Basics | XML Attributes

An XML element can include additional information called attributes. This article explains how to write attributes and how to decide between elements and attributes.

Writing Attributes

Write attributes inside an element’s start tag.

<elementName attributeName="attribute value">content</elementName>

Write an attribute name and value. Surround the value with quotation marks. For example:

<food id="001">banana</food>

An element can have multiple attributes. Separate each name-value pair with a space. Do not write the same attribute more than once in the same element.

<elementName attribute1="value1" attribute2="value2">content</elementName>

For example:

<food id="001" location="small refrigerator">banana</food>

Add attributes to the previous XML sample as follows.

<?xml version="1.0" encoding="UTF-8" ?>
<foods>
  <food id="001">
    <name>banana</name>
    <color>yellow</color>
  </food>

  <food id="002">
    <name>apple</name>
    <color>red</color>
  </food>
</foods>

Choosing Between Elements and Attributes

Additional data can be represented either as an attribute or as a child element. The following two documents represent the same information.

<food id="001">
  <name>banana</name>
</food>
<food>
  <id>001</id>
  <name>banana</name>
</food>

Either representation can be valid. Child elements are suitable for long text or content containing line breaks. Attributes are useful for metadata that does not need to be displayed as text, such as a file location.

An image-like element can use an attribute and remain empty.

<img src="http://www.devkuma.com/sample.jpg"/>

Choose consistent rules so that XML documents remain easy to understand.