What are attributes in XML?
Tags in XML hold content. The tags can also have attributes as a way of holding simple data. Attributes contain data related to specific elements in key-value pairs.
Attributes appear in the start tag:
Example
<tag key="value">content</tag>
In the above example:
<tagis the start tag.keyis the attribute.valueis the value of the attribute.contentis the content between the start and end tags./tag>is the end tag.
Example
<fileSize unit="kB">34.6</fileSize>
In the above example, the attribute is named unit and its value is kB.
Using attributes to describe song data
Let's say we have the following XML code to describe song data:
<song>
<title>XML Waltz</title>
<artist>The Extensible Extenders</artist>
<musicians>
<musician>Sally Flute</musician>
<musician>Derek Windpipe</musician>
</musicians>
</song>
In the example above, the first tag is for <song> and contains multiple tags nested beneath it. We can restructure this data using attributes:
<song title="XML Waltz" artist="The Extensible Extenders">
<musicians>
<musician name="Sally Flute"/>
<musician name="Derek Windpipe"/>
</musicians>
</song>
Sources
- MDN Web Docs
- Learn API Technical Writing: JSON and XML for Writers by Peter Gruenbaum
- W3 Schools