How to Display XML on a Web Page

Formatting XML for a Web Page

One question that comes up often is ‘How Do I Display XML on a Web Page?’ If you are familiar with CSS files for HTML, you will appreciate the concept of formatting. With the onset of the markup language XML, displaying data was a bit complicated. That changed with style sheets. You can show your XML by writing a CSS file to format the data and then linking the two files.

XML Sample

Let’s look at a small piece of XML code for a web page.

By adding a style sheet reference, you can format and display your XML code as a web page.

Style Sheet

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

  background-color: #ffffff;
  width: 100%;
  display: block;
  background-color: #999999;
  margin-bottom: 30pt;

This bit of code tells the processor what elements to display and how they should look on the web page. The first line of the formatting file will be the root element. The attributes for the root will apply to the page, but you change them for a 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 files with a .css extension. This will shorten the path information to identify the style sheet. In other words, upload both files, XML and CSS, to the same folder.

Linking the Documents

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.

Without a formatting file, such as CSS, XML will appear as basic text with an error that states the browser could not find a formatting document.