How to Use XML With CSS

Close up of XML code

kr7ysztof / Getty Images

If you're familiar with how CSS styles HTML pages, you'll appreciate the concept of formatting. At the onset of the XML markup language, displaying data was a bit complicated, but that changed with style sheets. 

By adding a stylesheet reference, you can format and display your XML code as a web page. Without CSS or some other formatting, XML appears as basic text with an error that states that the browser could not find a formatting document.

XML Styling Example

A simple style sheet only requires that you list the element and the formatting attributes necessary to display the data.

This bit of code tells the processor which elements to display and how they should look on the web page, like this:

The first line of the formatting file is the root element. The attributes for the root apply to the whole page, but you change them for each tag. This means you can designate the background color for the page and then again for each section.

Save this file to the same directory as your XML file, and make sure it has the .CSS file extension. 

Link to the CSS From the XML

At this point, these are two wholly separate documents. The processor has no idea that you want them to work together to create a web page.

You can fix this by adding a statement to the top of the XML document that identifies the path to the CSS file. The statement goes directly under the initial XML declaration statement, like this:

In this example, the CSS file is called products.css, which is why it's labeled as such in the XML document. Change that to whatever file name you chose for the CSS file.