Next page Previous page Start of chapter End of chapter

XML attributes

XML elements can have attributes. These are properties that hold for the entire element. An attribute has the syntax name = "value", where name is the attribute name and value is a string. The quotation marks enclosing the value can be single or double. An element may have any number of attributes, but their names must be distinct. The attribute order is not significant. An example follows:

<person born="23/06/1912" died="07/06/1954">
   <name>
      <first>Alan</first>
      <last>Turing</last>
   </name>
   <profession>computer scientist</profession>
   <profession>mathematician</profession>
   <profession>cryptographer</profession>
</person>

Some information might be equally encoded as attribute values or element contents. The following example shows how far you can go with attributes:

<person born="23/06/1912" died="07/06/1954">
  <name first="Alan" last="Turing"/>
  <profession value="computer scientist"/>
  <profession value="mathematician"/>
  <profession value="cryptographer"/>
</person>

So, what's the difference between using attributes and elements to hold information? The choice is up to you, but remind that each element can have no more than one attribute with a given name. Moreover, attributes are quite limited in structure: the value of an attribute is simply a string. A good rule is to use attributes for metadata about the element while elements for the information itself.

What are valid names for XML elements and attributes? A valid name for them is called an XML name and it formed as follows:

Next page Previous page Start of chapter End of chapter
Caffè XML - Massimo Franceschet