Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Styling XML with CSS - XML attributes?

Status
Not open for further replies.

tcstom

Programmer
Aug 22, 2003
235
GB
I'm familiar with both XML and CSS but have never tried to combine them before. I'm clear about how to apply styles to XML elements, but is it possible to vary that style based on attributes of those elements? Or can CSS styles only be applied to XML element tags? Thanks in advance for help.

Tom
emo_big_smile.gif
 
You could use style sheets and if-then-else clauses for the attribute values.
 
Thanks. Hadn't looked into XSLT before, but I've had a look at W3Schools and it's just what I need. I'd been under the impression that XSLT was just an alternative to CSS. How wrong I was! Thanks fawkes.

Tom
emo_big_smile.gif
 
Yes you can. For instance:
Code:
img[src="small.gif"] { border: 1px solid #000; }
This is not supported by many browsers though (notably IE 6). See:


For the moment, while CSS supported is lacking, I would stick to transforming XML with XSL into HTML. You could do something like this:

XML:
Code:
<xml>
  <node type="1">Type one node</node>
  <node type="2">Type two node</node>
</xml>
XSL:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="[URL unfurl="true"]http://www.w3.org/1999/XSL/Transform">[/URL]
  <xsl:template match="/">
    <xsl:apply-templates select="xml"/>
  </xsl:template>
  <xsl:template match="xml">
    <html>
      <head>
        <title>Test</title>
      </head>
      <body>
        <xsl:apply-templates select="node"/>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="node[@type = '1']">
    <h1>
      <xsl:value-of select="."/>
    </h1>
  </xsl:template>
  <xsl:template match="node[@type = '2']">
    <p style="color: blue;">
      <xsl:value-of select="."/>
    </p>
  </xsl:template>
</xsl:stylesheet>
This gives you a lot more control than pure CSS.

Jon

"I don't regret this, but I both rue and lament it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top