Skip Navigation LinksHome : CBC Classes : XML : CSS

CS216 XML - Adding CSS to an XML File

We're now going to move away from validating XML documents to learning how to display them If you open an XML file in a browser to look at the data it can be pretty bad. Even if you know what you're looking at and what you're looking for, there can be a lot to wade through. And looking at the raw data is not something I'd want any user to experience.

The first thing we'll look at is using CSS to format the data. You can think of this as what we do in Excel, when we take a table and make the table look prettier by formatting cells and borders. While this can make an improvement, it's still not a good way to present data to users. Luckily, the giant brains at the W3C invented a way for us to create reports called XSLT, which we'll look at after this section.

Hopefully you remember your CSS, but if you don't then you may want to review using the W3Schools CSS tutorials.

  1. Using CSS with XML
  2. Fundamental Display Types

Using CSS with XML

One of the simplest things you can do to make your XML data a little easier to look at is add some CSS. The CSS rules, selectors, properties and values are all the same as with HTML/XHTML; but there are a few differences in implementation.

The first is that the only way to attach the rules is to use an external file. (You actually could use a style element to embed your CSS rules, or the style attribute to create inline styles; but then you would have to have to add these to your schema. More trouble than it's worth.) And since there's no style element we can't use @import to link to the external CSS file. With XML there's a special xml directive xml-stylesheet that's used to create the link. It needs to be the second line in the XML data file as shown in the following example:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="cars.css" ?>

The css file can be in the same folder, or you can use the full URL if the file is on another computer.

Another difference is that there's no body or html elements. So if you want to set properties for the entire document and use inheritance you will have to set them on the dataroot element, what ever it is.


Fundamental Display Types

The other huge difference from using CSS with XML and using CSS with HTML/XHTML is that by default all of the XML elements are displayed inline.