RE: [xsl] Choosing Elements

Subject: RE: [xsl] Choosing Elements
From: "Jacoby, Peter R." <PJACOBY@xxxxxxxxxxxx>
Date: Tue, 16 Jul 2002 14:52:51 -0400
Jennifer,

> My XML file looks a little like this:
  <books>
> 	<Book>
> 		<Name>Sample</Name>
> 		<Parameter>
> 			<Name>Branch</Name>
> 			<Value>56789</Value>
> 		</Parameter>
>                 <Parameter>
> 			<Name>Division</Name>
> 			<Value>56789</Value>
> 		</Parameter>
> 	</Book>
> 	<Book>
> 		<Name>Sample2</Name>
> 		<Parameter>
> 			<Name>Branch</Name>
> 			<Value>7890</Value>
> 		</Parameter>
> 	</Book>
  </books>

 I added a <books> element as a wrapper because you had no root node in your
example


> Where there can be any number of Books and Books can
> have any number of Parameters (they may or may not
> have the same Parameters). 

When you need to match an unknown number of different Parameter elements,
keys can be very useful.  They can be difficult to learn initially but are
well worth the time spent.  My solution creates a key that matches on the
Name child of each Parameter.

You then have to apply-templates to only the unique values in the key which
I do with generate-id.  I wasn't sure exactly what you wanted your html
select element to look like (as discussed earlier today the format can be a
matter of personal opinion) but I figured this would give you a start.


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

<xsl:key name="options" match="Book/Parameter" use="Name" />

<xsl:template match="books">
	<xsl:apply-templates select="Book/Parameter[generate-id(.) =
generate-id(key('options', Name))]"/>
</xsl:template>

<xsl:template match="Parameter">
	<xsl:value-of select="concat(Name,': ')" />
	<select name="{Name}">
		<xsl:for-each select="key('options', Name)">
			<option>
				<xsl:value-of select="Value" />
			</option>
		</xsl:for-each>
	</select>
	<br/>
</xsl:template>

<xsl:template match="text()"/>

</xsl:stylesheet>

Hope this helps.

-Peter 



 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread