3

I know that CSS can be used to control the presentation of (X)HTML in modern browsers. I was under the impression that this was possible for arbitrary XML as well. (Am I mistaken?)

A concrete example: given the following XML

<log>
  <entry revision="1">
    <author>J Random Hacker</author>
    <message>Some pithy explanation</message>
  </entry>
</log>

I'd like to associate a CSS with this XML such that when viewed in a modern (WebKit, FireFox) browser, I see something like:

+----------------------------------+
| revision | 1                     |
+----------------------------------+
| author   | J Random Hacker       |
+----------------------------------+
| message  | Some pithy explanation|
+----------------------------------+

Where my oh-so-beautiful ascii-art is meant to indicate some table-like layout.

That is: XML+CSS --> "pixels for user" instead of XML+XSLT --> XHTML+CSS --> "pixels for user".

My hope is that this approach could be simpler way (for me) to present XML documents that are already document-like in their structure. I'm also just plain curious.

John Topley
  • 113,588
  • 46
  • 195
  • 237
bendin
  • 9,424
  • 1
  • 39
  • 37

3 Answers3

6

It is indeed possible to use CSS to format an XML document.

W3 schools example

(The W3C do recommend using xslt to do this sort of thing instead CSS though)

alex77
  • 536
  • 2
  • 5
  • 12
  • Thanks! This is exactly the kind of example I was looking for to get me started. (Now why didn't I find that the last N times I tried to google myself and answer?) – bendin Nov 10 '08 at 21:37
  • Unfortunately you won't be able to do things like converting that revision="1" into a "cell" containing "1" with just CSS - this is where XSL Transformations come in - although it' a much steeper learning curve :D – mercutio Nov 10 '08 at 21:39
  • Its better than XSLT for displaying XML for printing, it has better printer specific functionality (e.g. page numbering, margins depending on printer paper size etc) and a simpler syntax, although there are a few visual XSL generators out there that make creating an XSL almost as easy. – PJUK Jun 23 '11 at 17:08
2

According to the specification, CSS should work with XML documents as well as HTML documents. Instead of selecting common HTML elements in your CSS code, you select your own elements in the CSS file, such as:

entry {
    display: block;
}
author {
    display: inline;
    font-weight: bold;
}
...

You can associate the CSS file to your XML file by inserting a similar line of code into your XML file:

<?xml-stylesheet href="common.css" type="text/css"?>
Daan
  • 6,952
  • 4
  • 29
  • 36
1

yes it is possible. you simply write a rule for each element:

author{
   display:block;
   color:#888888;
}

etc.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192