Next page Previous page Start of chapter End of chapter

Cascading Style Sheets

The names of XML elements describe the meaning of their contents. However, they say nothing about the presentation of the content. CSS is a language for describing the appearance of elements in a document. It does not change the markup of an XML document but simply applies the presentation rules to the existing content.

A CSS stylesheet is a list of style rules of the form:

selector {
property: value;
property: value;
...
}

where selector specifies the XML elements you want to apply the rule to, property specifies the style property (e.g. color) you want to apply to the selected elements, and value is the value (e.g. red) to assign to the style property. The pair property:value is called declaration. Comments are inserted using the /*...*/ format.

Here is an example taken from the book XML in a Nutshell (by E. R. Harold and W. S. Means). The goal is to render an XML document describing Marjorie Anderson's recipe for Southern Corn Bread. The chosen stylesheet is as follows:

/* Defaults for the entire document */
recipe  {
  font-family: "New York", "Times New Roman", serif; 
  font-size: 14pt; 
}

/* Make the dish look like a headline */
dish    {
  display: block; 
  font-family: Helvetica, Arial, sans-serif; 
  font-size: 20pt;
  font-weight: bold;
  text-align: center;
}

/* A bulleted list */
ingredient  {
  display: list-item; 
  list-style-position: inside;
} 

/* Format these two items as paragraphs */
directions, story {
  display: block; 
  margin-top: 12pt; 
  margin-left: 4pt;
}

For instance, the first rule specifies that the recipe element should be formatted using the New York font at 12 point size, or using Times New Roman if New York is not available, or using any serif font if both fonts are not available. This style cascades down the XML tree, that is, it applies to all descendant elements, which inherit this style, unless it is redefined at some descendant. In fact, the second rule overrides this style for the dish element and adds more style properties to render its content as a heading.

Here is the result of applying the stylesheet to the XML document.

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