Click to return to the XML (Extensible Markup Language) home page    
Choosing Between CSS and ...     Browsing XML Using XSL St...     Browsing XML Documents in...    
Web Workshop  |  XML (Extensible Markup Language)

How to Write a CSS Style Sheet for Browsing XML


This section illustrates how you can create a CSS style sheet for a simple XML document.

The sample XML document below represents a restaurant review. It contains several distinct sections representing different types of information important to the review. The first section is contained in an element named "restaurant" and provides data about the restaurant—name, address, phone. The next section is the "review" element, which contains data about this review—the reviewer's name, the date of the review, and the number of stars it received. The third section is the "body" of the review, and the final section contains an excerpt of the restaurant's menu.

<?xml version='1.0'?>
<story>
  <restaurant>
    <name>Red Apple Inn</name>
    <address>
      <street>3100 Longview Lane</street>
      <city>Palabro</city>
      <state>Wyoming</state>
    </address>
    <phone>123-555-1212</phone>
  </restaurant>
  
  <review>
    <rating stars="4">****</rating>
    <date>December 29, 1998</date>
    <reviewer><person>Louis Framptenheimer</person></reviewer>
  </review>
  
  <body>
    <p><summary>The small town of <city>Palabro</city> seems like
    an unlikely place for a high-class culinary establishment, but
    the <self>Red Apple Inn's</self> Chef <person>Alex
    Choperoni</person> is earning a national reputation for innovative
    dishes.</summary>  And rightly so, if this reviewer's recent
    culinary experience is any example.</p>
  
    <p>Within striking distance from the ski slopes at <city>Jackson
    Hole</city>, the <self>Red Apple Inn</self> is a completely
    restored Victorian hotel, and offers a warm and elegant atmosphere and
    gracious service.  The upscale clientele includes regular
    appearances by movie stars <person>Drew Barrymore</person> and
    <person>Matthew Broderick</person>.  Reservations are a must, and
    during the ski season it is not uncommon for the dining room to
    be booked solid six weeks in advance.</p>
    
    <p>It is hard to go wrong with a menu this packed with interesting
    choices.  The crab cakes are especially fine with a thin crisp
    crust that opens with a gentle prod of a fork to reveal a light,
    moist, almost mousse-like interior with a rich nutty flavor.</p>
  
    <p>The <self>Red Apple Inn</self> boasts one of the finest wine
    cellars in the region.  None of the dishes we sampled were less than
    outstanding. Here are a few of the selections from the daily menu.</p>
  </body>
    
  <menu>
    <appetizer>
      <description>Crab cakes with a creamy dill sauce served with crispy
        herbed daikon fries</description>
      <price>$23</price>
    </appetizer>
    <entree>
      <description>Braised jumbo sea scallops on a tomato beurre
        blanc</description>
      <price>$39</price>
    </entree>
    <entree>
      <description>Free-range chicken breast stuffed with morels in a
        brandy/green-peppercorn sauce</description>
      <price>$31</price>
    </entree>
    <entree>
      <description>Tarragon roast pork loin on a bed of ginger apple slaw
        and caramelized onions</description>
      <price>$34</price>
    </entree>
  </menu>
  
</story>

Notice that the XML tags used in this article have very little to do with presentation. There are no assumed layout, fonts, or colors. This information will be conveyed in the style sheet.

The Using CSS article contains information about how to write a style sheet in CSS for use with HTML. These style sheets augment or override the default formatting behavior built into HTML. For XML, the default formatting behavior is "display:inline". One of the first tasks in writing a CSS style sheet for XML is setting the display property to "block" or "none" for many of the elements.

Here's how you can begin to create a CSS style sheet for the restaurant review example. This style sheet assigns the display property the value "block" for the main sections.

story      { display: block; }
restaurant { display: block; }
review     { display: block; }
body       { display: block; }
menu       { display: block; }

Save this document as review.css. Now add the style sheet processing instruction (PI) to the beginning of the XML document (before the "story" element) so that it can locate our newly created style sheet.

<?xml-stylesheet type="text/css" href="review.css" ?>

At this point, opening the XML document in the browser will provide a rudimentary display of the XML document. Additional CSS formatting properties can be added to augment these rules, and new rules can be created for the remaining XML elements. Here is an augmented set of style rules for the menu element and its children.

menu
{
  display: block;
  border: 2px solid black;
  padding: 1em;
  background-color: #888833;
  color: #FFFFDD;
  font-family: Times, serif;
  font-style: italic;
  text-align: center;
}

appetizer
{
  display: block;
  margin-bottom: .4em;
}

entree
{
  display: block;
  margin-bottom: .4em;
}

price
{
  display: inline;
  font-weight: bold;
  font-style: normal;
}

description
{
  display: inline;
}

To complete this style sheet, additional rules must be added to handle the remaining elements in the source document.

Using Namespaces with CSS

Namespaces must be declared on the document element when using XML with a CSS style sheet. Locally scoped namespaces will parse correctly, but CSS does not currently describe a mechanism for resolving namespace prefixes, thus CSS rules might not apply correctly to elements in the locally scoped namespace. Placing all namespace declarations on the document element ensures that they are all "global" and thus there will be no collision of prefixes. The default namespace cannot be used—all namespaced elements must have an explicit prefix. In addition, CSS selectors can specify a namespaced element only by its prefix, so ensure that the prefix is consistent between the XML document and the style sheet.

Here is an example of a style sheet for elements with the "HTML" prefix.

HTML\:IMG {
  border: 2px solid black;
}

HTML\:A:visited HTML\:IMG {
  border-color: grey;
}

HTML\:A:active HTML\:IMG {
  border-color: red;
}

HTML\:A:link HTML\:IMG {
  border-color: blue;
}

Notice that the ":" namespace character must be escaped by a leading backslash to differentiate it from a pseudoclass.

Using the HTML Namespace

The HTML namespace is treated specially when browsing XML with CSS. Elements from the HTML namespace are displayed as they would in HTML. This allows access to capabilities not yet provided by CSS. Some examples of useful HTML elements to embed are <TABLE>, <A>, <IMG>, <SCRIPT>, and <STYLE>.

For example, you can add a link and logo to the restaurant review sample. First, you must declare the HTML namespace at the top of the document and then use the "HTML" prefix on the embedded HTML elements. Note that HTML embedded this way must be well-formed XML, so the <IMG> element needs a minimized end tag.

<story xmlns:HTML="http://www.w3.org/Profiles/XHTML-transitional">
  ...
  <restaurant>
    <name>Red Apple Inn</name>
    <logo>
      <HTML:A href="javascript:alert('Visit the Red Apple Inn!')">
        <HTML:IMG src="red-apple.gif" height="50" width="200"/>
      </HTML:A>
    </logo>
    ...

Note that in Microsoft® Internet Explorer 5 the prefix must remain "HTML" or "html" for the elements to be interpreted as HTML elements.

An <HTML:STYLE> block can be used to embed a CSS style sheet within an XML document. This block will augment any style sheets pointed to by style sheet PIs. When there is no external style sheet, there still must be a style sheet PI present to indicate that the XML document should be displayed using the CSS style sheet language, even though no "href" attribute is specified.

The following example shows how the review.css style sheet could be embedded into the XML document using the HTML namespace, the <HTML:STYLE> element, and the style sheet PI without an "href" attribute.

<?xml version="1.0"?>
<?xml-stylesheet type="text/css"?>
<story xmlns:HTML="http://www.w3.org/Profiles/XHTML-transitional">
  <HTML:STYLE>
    story
    {
      display: block;
      font-family: Arial, Helvetica, sans-serif;
      font-size: small;
      width: 30em;
    }

    restaurant
    {
      display: block;
      padding: 1.2em;
      font-size: x-small;
      margin-bottom: 1em;
    }
    ...
  </HTML:STYLE>
  <restaurant>
    ...

Try it! Here are the final versions of the restaurant review sample. These two versions display identically, but reference the style sheet in different ways:

Download Download these samples.



Back to topBack to top

Did you find this topic useful? Suggestions for other topics? Write us!

© 1999 Microsoft Corporation. All rights reserved. Terms of use.