The Cascading Style Sheets can be added to XML file to add style to it’s contents. It can be done by adding one or more processing instructions with target of xml-stylesheet in document’s prolog. Using CSS for styling XML is not a recommended method by W3C. Instead it is suggested to use XSLT.

Syntax for XML stylesheets

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

The example below displays the XML file with stylesheet included from CSS file.

Example of XML working with CSS

StyleDemo.css

<?xml version="1.0" encoding="UTF-8"?>

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

<root>

      <sports>

    <game>cricket</game>

    <player>Sachin Tendulkar</player>

    <trophy>Cricket World Cup</trophy>

      </sports>

     

      <sports>

    <game>chess</game>

    <player>Vishwanathan Anand</player>

    <trophy>World Chess Champion</trophy>

      </sports>

     

    <sports>

    <game>tennis</game>

    <player>Leander Paes</player>

    <trophy>Davis Cup</trophy>

      </sports>

     

    <sports>

    <game>swimming</game>

    <player>Nisha Millet</player>

    <trophy>Swimming World Cup</trophy>  

      </sports>

</root>

Game.css

sports{ 

  display:block;

}

game{ 

   text-transform: uppercase;

   text-decoration: underline;

}

player{

   color:green;

}

trophy{

   color:red;

}

Output:

CRICKET Sachin Tendulkar Cricket World Cup

CHESS Vishwanathan Anand World Chess Champion

TENNIS Leander Paes Davis Cup

SWIMMING Nisha Millet Swimming World Cup

 

›› go to examples ››