How to apply CSS to XML

Sometimes there will be times when you’ll need to take a body of XML information and apply CSS styles to it.  Luckily, it’s not too hard to do.  Let’s say you have an XML document that looks like this (the content about the movie is not accurate):

<?xml version=”1.0″ encoding=”utf-8″ standalone=”yes”?>
<movie>
<title>Monty Python and the Holy Grail</title>
<rating>PG-13</rating>
<reviews>
<rotten>100%</rotten>
<metacritic>100%</metacritic>
</reviews>
<director compensation=”$100,000,000″>Some really funny guy</director>
<boxoffice>$1,000,000,000,000</boxoffice>
</movie>

If I wanted to style the title, rating, director, and the other tags I would need to apply CSS to this file.  To do that you would need this line of code:

<?xml-stylesheet type=”text/css” href=”somecss.css”?>

You would put this under the first line of the XML making it look like this:

<?xml version=”1.0″ encoding=”utf-8″ standalone=”yes”?>
<?xml-stylesheet type=”text/css” href=”somecss.css”?>
<movie>
<title>Monty Python and the Holy Grail</title>
<rating>PG-13</rating>
<reviews>
<rotten>100%</rotten>
<metacritic>100%</metacritic>
</reviews>
<director compensation=”$100,000,000″>Some really funny guy</director>
<boxoffice>$1,000,000,000,000</boxoffice>
</movie>

This is saying, use and apply the CSS file called somecss.css to the XML page.  With the way this code is written, you’ll need to make sure that the CSS file is in the exact same spot as your XML file.  Once you’ve done this, the two files are connected and you can test to make sure it works by putting some styles in the somecss.css file like this:

title{
color:red;
font-size:22px;
text-decoration:underline;
}

If you see the content in the title tags change, you did it right.  If you’d like to learn more be sure to check out our web design/development courses.  Have an amazing day!

Leave a Reply

Your email address will not be published. Required fields are marked *