我有以下XML代码:
<root>
<options>
<companies>
<company url="http://www.brown.com">Brown LLC</company>
<company url="http://www.yellow.com">Yellow LLC</company>
<company url="http://www.black.com">Black LLC</company>
<company url="http://www.bourdeaux.com">Bourdeaux LLC</company>
<company url="http://www.orange.com">Orange LLC</company>
</companies>
</options>
</root>
Run Code Online (Sandbox Code Playgroud)
我需要做两件事:
使用公司节点中找到的唯一首字母构建html下拉列表.如:
<select id="colors">
<option value="B">B</option>
<option value="O">O</option>
<option value="Y">Y</option>
</select>
Run Code Online (Sandbox Code Playgroud)构建一个辅助下拉列表,列出所有以特定字母开头的公司.如:
<select id="companiesB">
<option value="http://www.black.com">Black LLC</option>
<option value="http://www.bordeaux.com">Bordeaux LLC</option>
<option value="http://www.brown.com">Brown LLC</option>
</select>
Run Code Online (Sandbox Code Playgroud)任何帮助,将不胜感激!
首先,您需要定义一个键,将所有公司元素"组合" 在一起,共享相同的第一个字母
<xsl:key name="companyLetter" match="company" use="substring(text(), 1, 1)" />
Run Code Online (Sandbox Code Playgroud)
接下来,您将迭代所有公司元素
<xsl:for-each select="options/companies/company">
Run Code Online (Sandbox Code Playgroud)
但是,您只想处理公司元素,如果它是第一个字母的第一个元素出现.您可以通过在第一个字母的键中查找第一个元素来查看它是否相同.元素比较使用generate-id()函数完成
<xsl:variable name="firstLetter" select="substring(text(), 1, 1)" />
<xsl:if test="generate-id(.) = generate-id(key('companyLetter', $firstLetter)[1])" >
Run Code Online (Sandbox Code Playgroud)
完全放弃这个
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:key name="companyLetter" match="company" use="substring(text(), 1, 1)"/>
<xsl:template match="/root">
<select id="colors">
<xsl:for-each select="options/companies/company">
<xsl:sort select="text()"/>
<xsl:variable name="firstLetter" select="substring(text(), 1, 1)"/>
<xsl:if test="generate-id(.) = generate-id(key('companyLetter', $firstLetter)[1])">
<option>
<xsl:attribute name="value">
<xsl:value-of select="$firstLetter"/>
</xsl:attribute>
<xsl:value-of select="$firstLetter"/>
</option>
</xsl:if>
</xsl:for-each>
</select>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
对于第二个下拉列表,您可以使用命名模板,该模板将字母作为参数传递.您可以使用与上面相同的键查找该字母的所有元素.
<xsl:template name="Companies">
<xsl:param name="firstLetter"/>
<select>
<xsl:attribute name="id">
<xsl:value-of select="$firstLetter"/>
</xsl:attribute>
<xsl:for-each select="key('companyLetter', $firstLetter)">
<xsl:sort select="text()"/>
<option>
<xsl:attribute name="value">
<xsl:value-of select="@url"/>
</xsl:attribute>
<xsl:value-of select="text()"/>
</option>
</xsl:for-each>
</select>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
例如,要调用模板,只需传递所需参数即可
<xsl:call-template name="Companies">
<xsl:with-param name="firstLetter">B</xsl:with-param>
</xsl:call-template>
Run Code Online (Sandbox Code Playgroud)
当然,如果你想要显示所有可能的首字母的所有下拉菜单,你可以把它作为for-each循环.
| 归档时间: |
|
| 查看次数: |
3361 次 |
| 最近记录: |