3D-kreativ
3D-kreativ

Reputation: 9301

CSS style and XSLT?

If I select a DIV tag in a XHTML file with XSLT, like //*[@id='background'] How do I add a style, like a background color or other CSS styles like borders to the DIV? And if I have a list inside the DIV ID=background, how can I style the list, like removing the bullets? :)

Upvotes: 3

Views: 10379

Answers (1)

Emiliano Poggi
Emiliano Poggi

Reputation: 24816

This is really easy with XSLT. For instance, your input is:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title></title>
    </head>
    <body>
        <div id="background">
            <ul style="list-style-type: bullet">
                <li>Coffee</li>
                <li>Tea</li>
                <li>Milk</li>
            </ul>       
        </div>
    </body>
</html>

You can use the identity transform to copy the input XML as is, and override the nodes of interest:

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:x="http://www.w3.org/1999/xhtml"
    exclude-result-prefixes="x">

    <xsl:output method="xml" indent="yes"/>

    <xsl:strip-space elements="*"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="x:div[@id='background']">
        <xsl:copy>
            <xsl:attribute name="style">
                <xsl:text>border-style:solid;border-width:medium</xsl:text>
            </xsl:attribute>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="x:ul[ancestor::*
        [name()='div' and @id='background']]/@style">
        <xsl:attribute name="style">
            <xsl:text>list-style-type: none</xsl:text>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

The output will be:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
   <head>
      <title></title>
   </head>
   <body>
      <div style="border-style:solid;border-width:medium" id="background">
         <ul style="list-style-type: none">
            <li>Coffee</li>
            <li>Tea</li>
            <li>Milk</li>
         </ul>
      </div>
   </body>
</html>

Upvotes: 5

Related Questions