Re: [xsl] convert nested elements, ID's and classes to CSS declaration

Subject: Re: [xsl] convert nested elements, ID's and classes to CSS declaration
From: "Jay Bryant" <jay@xxxxxxxxxxxx>
Date: Wed, 21 Mar 2007 12:30:33 -0500
Hello,

I searched for this all over and couldn't find a
solution.  I want to take the following XML:

<root>
<file>
<element/>
</file>
<file id="a">
<element id="a"/>
</file>
<file class="b">
<element class="b"/>
</file>
<file id="c" class="d" not="1" this="2">
<element id="c" class="d" not="1" this="2"/>
</file>
</root>


#### and output something this ####



root root file root file element root file #a root file #a element #a root file .b root file .b element .b root file #c .d root file #c .d element #c .d


#### ignoring any attributes that are not "id" or "class" and containing all ancestor elements and id's and classes no matter what the element name is or how many levels deep. I'd like to use this for auto generating CSS declarations from XHTML snipits, I can deal with removing redundant rows manually. Below is the closest I've gotten which only strips the XML to the elements and attributes I'm interested in, but doesn't format it or list ancestor elements, id's and classes (I'm a beginner at XSLT) thanks! ####


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

Here's one way:


<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>


<xsl:output method="text" indent="no"/>

<xsl:template match="*">
<xsl:for-each select="ancestor-or-self::*">
<xsl:value-of select="name()"/><xsl:text> </xsl:text>
<xsl:if test="@id">#<xsl:value-of select="@id"/><xsl:text> </xsl:text></xsl:if>
<xsl:if test="@class">.<xsl:value-of select="@class"/><xsl:text> </xsl:text></xsl:if>
</xsl:for-each>
<xsl:apply-templates/>
</xsl:template>


</xsl:stylesheet>

Jay Bryant
Bryant Communication Services


Current Thread