Pages

Tuesday, December 17, 2013

Apply a CSS Stylesheet to your XML files

CSS is not just for HTML. When you need a quick glimpse of your XML in a more "format-friendly" presentation, you can easily use Cascading Style Sheets to view the XML. CSS is a simple stylesheet mechanism that allows you to attach styles to XML-based content. Listing A shows an XML file that contains information about a purchase order. The xml-stylesheet processing instruction applies the CSS Stylesheet called po.css to the XML.

Listing A: po.xml
<?xml version="1.0"?>
<?xml-stylesheet href="po.css" type="text/css"?>
<purchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.my-company.com/PO po.xsd">
   <billTo>
      <name>Robert Smith</name>
      <street>18 Park Avenue</street>
      <city>Some Town</city>
      <state>AR</state>
      <zip>95819</zip>
   </billTo>
   <Items>
      <item partNum="833-AA">
         <productName>Lapis necklace</productName>
         <quantity>2</quantity>
         <price>99.95</price>
         <comment>Need this for the holidays!</comment>
         <shipDate>2005-12-05</shipDate>
      </item>
      <item partNum="748-OT">
         <productName>Diamond heart</productName>
         <quantity>1</quantity>
         <price>248.90</price>
         <comment>Valentine's day packaging.</comment>
         <shipDate>2005-02-14</shipDate>
      </item>
   </Items>
</purchaseOrder>


The CSS Stylesheet for this XML uses a wildcard selector to match all elements. The rësult is each element displays as its own block. The content of the name element appears bold. This CSS stylesheet also illustrates the cascading nature of CSS. Notice the margin is set at the root element level and all descendant elements inherit the margin-left property.

Listing B: po.css
/*
css style rules for purchaseOrder xml
*/
*{
    display: block;
}
purchaseOrder{
    margin-left: 1em;
}
name{
    font-weight: bold;
}


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.