这是一种更有效的基于键的查找:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pLookupPath" select="'file:///c:/temp/delete/lookup2.xml'"/>
<xsl:param name="pLang" select="'en_GB'"/>
<xsl:key name="kLookup" match="text/*"
use="concat(../@name, '+', name())"/>
<xsl:variable name="vDict" select="document($pLookupPath)"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match=
"div/text()
[starts-with(., '[')
and substring(., string-length(), 1) = ']'
]">
<xsl:variable name="vTextName" select="substring(., 2, string-length() -2)"/>
<xsl:for-each select="$vDict">
<xsl:value-of select=
"(key('kLookup', concat($vTextName, '+', $pLang))
|
key('kLookup', concat($vTextName, '+', substring-before($pLang, '_')))
)[1]
"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
如果提供的翻译文件位于c:/temp/delete/lookup2.xml
并且何时对提供的 XML 文档应用转换:
<html>
<div>Lot's of html</div>
<div>[property.to.match]</div>
<div>[other.property.to.match]</div>
</html>
产生了想要的正确结果:
<html>
<div>Lot's of html</div>
<div>The British translation</div>
<div>The other language localized, but non locale based generic translation</div>
</html>
二、XSLT 2.0 解决方案:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pLookupPath" select="'file:///c:/temp/delete/lookup2.xml'"/>
<xsl:param name="pLang" select="'en_GB'"/>
<xsl:key name="kLookup" match="text/*"
use="concat(../@name, '+', name())"/>
<xsl:variable name="vDict" select="document($pLookupPath)"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match=
"div/text()
[starts-with(., '[') and ends-with(., ']')]">
<xsl:variable name="vTextName" select="substring(., 2, string-length() -2)"/>
<xsl:sequence select=
"(key('kLookup', concat($vTextName, '+', $pLang), $vDict)
,
key('kLookup', concat($vTextName, '+', substring-before($pLang, '_')),
$vDict)
)[1]
"/>
</xsl:template>
</xsl:stylesheet>