XML, XSLT Tabellenzeilen abhängig von Attributwert einfärben.

Thomas Darimont

Erfahrenes Mitglied
Hallo!

Hier mal eine (der vielen) Möglichkeiten das gewünschte (siehe Topic) zu erreichen.

Data.xml:

Code:
<?xml version="1.0" ?>
<entries contentTitle="My Content">
	<entry attribute0="a">
		Some Data0
	</entry>
	
	<entry attribute0="a">
		Some Data1
	</entry>
	
	<entry attribute0="b">
		Some Data2
	</entry>
	
	<entry attribute0="b">
		Some Data3
	</entry>
	
	<entry attribute0="a">
		Some Data4
	</entry>
</entries>

Die Transform.xsl:

Code:
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:template match="/">
		<html>
			<head>
				<title><xsl:value-of select="entries/@contentTitle"/></title>
			</head>
			<body>
				<xsl:apply-templates/>
			</body>
		</html>
	</xsl:template>
	
	<xsl:template match="entries">
		<table border="1">
			<xsl:for-each select="entry">
				<xsl:call-template name="zeile"/>
			</xsl:for-each>			
		</table>
	</xsl:template>
	
	<xsl:template name="zeile">
		<tr>
			<!--bgcolor attribut von übergeordnetem Element (tr) je nach
			    Situation ändern -->
			    
			<xsl:if test="@attribute0='a'">
				<xsl:attribute name="bgcolor">#00FF00</xsl:attribute>
			</xsl:if>
			
			<xsl:if test="@attribute0='b'">
				<xsl:attribute name="bgcolor">#0000FF</xsl:attribute>
			</xsl:if>
			
			<td>
				<xsl:value-of select="text()"/>
			</td>
		</tr>
	</xsl:template>
</xsl:stylesheet>

und hier die Ausgabe:
Code:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-16">
<title>My Content</title>
</head>
<body>
<table border="1">
<tr bgcolor="#00FF00">
<td>
		Some Data0
	</td>
</tr>
<tr bgcolor="#00FF00">
<td>
		Some Data1
	</td>
</tr>
<tr bgcolor="#0000FF">
<td>
		Some Data2
	</td>
</tr>
<tr bgcolor="#0000FF">
<td>
		Some Data3
	</td>
</tr>
<tr bgcolor="#00FF00">
<td>
		Some Data4
	</td>
</tr>
</table>
</body>
</html>

HTH,

gruß Tom
 
Zurück