1. Computing

Discuss in my forum

Formatting XML with a Cascading Style Sheet (CSS)

XML and CSS

By

One quick way to format your XML code is with a CSS style sheet. Cascading Style Sheets (CSS) allow designers more flexibility when creating the look for a web page. If you write HTML with formatting embedded in the code, you are destined to repeat the same instructions over and over. Then when it comes time to make changes, you must hunt through lines and lines of code to find the passage to makeover. CSS is a mechanism that allows web page authors to distinguish formatting from the structure.

In a sense, you can apply this same logic to XML documents. Without formatting, XML does remarkably little. It is the instructions you provide that makes the wheel turn and produces your XML in a useable format. There are more complex ways to format XML. For example, XSL is also a style sheet but combines validation rules with formatting instructions. If your focus is the look, you can use a more straightforward approach and link to a basic CSS file.

Sample XML

<?xml version="1.0"?>
<xml-stylesheet type= "text/css" href= "my_css.css"?>
<Inventory>
  <bikes>
    <women>
      <size>24 inch </size>
      <color>black</color>
      <manu>Huffy</manu>
    </women>
  </bikes>
</inventory>

Here is a short piece of XML code for bike inventory. The notable line in the code is:

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

This links the XML document to a CSS style sheet called my_css.css. In other words, the browser sees this line and knows to look for a CSS formatting file.

Sample CSS

All that is left to do is write the corresponding CSS code and save it to a file.

Inventory {
  background-color: #ffffff;
  width: 100%;
}

This first section sets the format for the entire page by using the root element for the XML file, Inventory. Now we can apply individual formats to each section.

bikes {
  display: block;
  margin-bottom: 30pt;
  margin-left; 0;
}

The browser sees bikes and looks for the corresponding element tag in the XML file. You can create individualized fonts, section colors and formatting instructions per element tag. As long as you link the XML file to the CSS file, the browser will connect the two.

Limitations

This is a fast and dirty way to format your XML code. In the design stage, CSS will allow you to create the look of the page without worrying about much else. CSS is simple by design. There are limitations for using it exclusively. For example, CSS does not care about data types or namespaces. It is strictly formatting, but there may be a time when formatting is all that is required. In those situations, CSS is the quickest way to go.

  1. About.com
  2. Computing
  3. Web Design / HTML
  4. XML
  5. Beginning XML
  6. XML and CSS

©2014 About.com. All rights reserved.