我需要按特定顺序获取属性,因此我在一组特定名称上使用循环。我想做@ $属性或@之类的东西。但只是使用。给我的名字本身,而不是我想要的属性的价值。
基本上不是每行都说“标题”和“艺术家”,而是想要实际的标题和艺术家。
的hello.xml:
<?xml version="1.0" encoding="UTF-8"?>
<results>
<r title="Empire Burlesque" artist="Bob Dylan" />
<r title="Hide your heart" artist="Bonnie Tyler" />
<r title="Greatest Hits" artist="Dolly Parton" />
</results>
hello.xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template name="boxNames"> <!-- not used as template -->
<name>title</name>
<name>artist</name>
</xsl:template>
<xsl:template match="/">
<xsl:variable name="boxNames" select="document('')/xsl:stylesheet/xsl:template[@name='boxNames']/name" />
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<xsl:for-each select="$boxNames">
<th style="text-align:left"><xsl:value-of select="." /></th>
</xsl:for-each>
</tr>
<xsl:for-each select="results/r">
<tr>
<xsl:for-each select="$boxNames">
<td><xsl:value-of select="."/></td>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
输出:
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th style="text-align:left">title</th>
<th style="text-align:left">artist</th>
</tr>
<tr>
<td>title</td>
<td>artist</td>
</tr>
<tr>
<td>title</td>
<td>artist</td>
</tr>
<tr>
<td>title</td>
<td>artist</td>
</tr>
</table>
</body>
</html>Execution time: 88.941623ms
答案 0 :(得分:0)
我不明白为什么你不能简单地将你想要的列的顺序硬编码到样式表本身,例如:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/results">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<!-- header -->
<tr>
<th>title</th>
<th>artist</th>
</tr>
<!-- body -->
<xsl:for-each select="r">
<tr>
<td>
<xsl:value-of select="@title"/>
</td>
<td>
<xsl:value-of select="@artist"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
但是如果你真的想在一个单独的列表中枚举列名,那么试试这个:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="columns">
<name>title</name>
<name>artist</name>
</xsl:variable>
<xsl:variable name="column-names" select="document('')/*/xsl:variable[@name='columns']/name" />
<xsl:template match="/results">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<!-- header -->
<tr>
<xsl:for-each select="$column-names">
<th>
<xsl:value-of select="." />
</th>
</xsl:for-each>
</tr>
<!-- body -->
<xsl:for-each select="r">
<xsl:variable name="row" select="."/>
<tr>
<xsl:for-each select="$column-names">
<td>
<xsl:value-of select="$row/@*[name()=current()]"/>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>