我正在开发一个XSLT转换,它只能在XPath 1.0中使用xslt 1.0。 假设我有以下xml,我想选择original_file_name属性以“.prt”结尾的对象。我怎么能这样做?
<object>
<object>
<attribute name="original_file_name">file1.qaf</attribute>
<attribute name="otherAttribute1">val</attribute>
<attribute name="otherAttribute2">val</attribute>
</object>
<object>
<attribute name="original_file_name">file2.tso</attribute>
<attribute name="otherAttribute1">Second guess</attribute>
<attribute name="otherAttribute2">val</attribute>
</object>
<object>
<attribute name="original_file_name">file3.prt</attribute>
<attribute name="otherAttribute1">First guess!</attribute>
<attribute name="otherAttribute2">val</attribute>
</object>
</object>
对于XSLT 2.0,我找到了一个解决方案,但我无法摆脱XPath 1.0中不支持的索引。你有任何解决方案的提示吗?
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="xml" encoding="iso-8859-1" indent="yes"/>
<xsl:template match="/object">
<xsl:variable name="fileIndex">
<xsl:call-template name="identifyFile">
<xsl:with-param name="fileNames" select="object/attribute[@name='original_file_name']"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="fileObj" select="object[position()=$fileIndex]"/>
<!-- do sth. with fileObj -->
<xsl:copy-of select="$fileObj" />
</xsl:template>
<xsl:template name="identifyFile">
<xsl:param name="fileNames"/>
<xsl:choose>
<!-- add other file extensions here -->
<xsl:when test="$fileNames['.prt'=substring(., string-length() - 3)]">
<xsl:value-of select="index-of($fileNames, $fileNames['.prt'=substring(., string-length() - 3)])" />
</xsl:when>
<xsl:when test="$fileNames['.tso'=substring(., string-length() - 3)]">
<xsl:value-of select="index-of($fileNames, $fileNames['.tso'=substring(., string-length() - 3)])" />
</xsl:when>
<!-- if no known file extension has been found, just take the default one. -->
<xsl:otherwise>
<xsl:value-of select="1"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
编辑:在第一步中过多地简化了问题:)。我添加了第二个文件扩展名,如果找不到第一个文件扩展名,应该搜索它。因此,如果在示例中没有'.prt'文件,则应该采用'.tso'文件。
答案 0 :(得分:1)
如果您只想根据条件选择XPath表达式
object[attribute[@name='original_file_name' and substring(., string-length() - 3) = '.prt']]
copy-of
中的就足够了。使用您编辑的样本我认为您只需要
<xsl:template match="/object">
<xsl:variable name="fileNames" select="object/attribute[@name='original_file_name']"/>
<xsl:choose>
<!-- add other file extensions here -->
<xsl:when test="$fileNames['.prt'=substring(., string-length() - 3)]">
<xsl:copy-of select="$fileNames['.prt'=substring(., string-length() - 3)]" />
</xsl:when>
<xsl:when test="$fileNames['.tso'=substring(., string-length() - 3)]">
<xsl:copy-of select="$fileNames['.tso'=substring(., string-length() - 3)]" />
</xsl:when>
<!-- if no known file extension has been found, just take the default one. -->
<xsl:otherwise>
<xsl:copy-of select="$fileNames[1]"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>