将 xml 转换为 html,我想根据存储在 xml 文档中其他位置的信息为元素分配一个类名。为此,我需要将当前节点的属性值插入到 XPath 中。我不知道该怎么做。
鉴于此 xml:
<?xml version="1.0"?>
<Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
<Styles>
<Style ss:ID="cell-ID" ss:Name="classname">
</Style>
</Styles>
<Worksheet>
<Cell ss:StyleID="cell-ID">test</Cell>
</Worksheet>
</Workbook>
我使用了以下 XSL,但带有箭头指针的行不起作用:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
exclude-result-prefixes="ss"
version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<xsl:element name="style">
<xsl:for-each select="Workbook/Styles/Style">
#<xsl:value-of select="@ss:ID"/>
<xsl:if test="@ss:Name">, .<xsl:value-of select="@ss:Name" /></xsl:if> { ... }
</xsl:for-each>
</xsl:element>
<xsl:for-each select="Workbook/Worksheet/Cell">
<xsl:element name="div">
<xsl:attribute name="class">default</xsl:attribute>
<xsl:if test="@ss:StyleID">
<xsl:attribute name="id">
<xsl:value-of select="@ss:StyleID"/>
</xsl:attribute>
<xsl:attribute name="class">
==> <xsl:value-of select="//Style[@ss:ID=@ss:StyleID]/@ss:Name"/>
</xsl:attribute>
</xsl:if>
<xsl:value-of select="."/>
</xsl:element>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
所需的输出是
<style>
#cell-ID, .classname { ... }
</style>
<div class="classname" id="cell-ID">test</div>
但类名保持为空。
非常感谢任何帮助。
答案 0 :(得分:2)
XSLT 具有用于解决交叉引用的内置 key 机制。
考虑这个最小的例子:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
exclude-result-prefixes="ss">
<xsl:key name="styl" match="Style" use="@ss:ID" />
<xsl:template match="/Workbook">
<html>
<body>
<xsl:for-each select="Worksheet/Cell">
<div class="{key('styl', @ss:StyleID)/@ss:Name}">
<xsl:value-of select="."/>
</div>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
应用于您问题中的输入,这将产生:
结果
<html>
<body>
<div class="classname">test</div>
</body>
</html>
注意 (1) literal result elements 和 (2) attribute value template 的使用。