How to do I18N with xsl and xml

雨燕双飞 提交于 2019-12-09 18:15:13

问题


I am trying to do a page in different languages with xml/xsl. I want to have only one xml and one xsl. On my page Url I have a parameter pLanguage that I think I can use to look if I have selected English or Dutch.

I tried with this code but I don’t know how I put it together:

First I make variables of all the words who has to been translated like this:

<xsl:variable name="lang.pageTitle" select="'This is the title in English'"/>

To get the pageTitle in the template I now can use

<xsl:value-of select="$lang.pageTitle"/>

I thought to replace the first line of code above by using a if-else statement to test if my choosen language is EN or NL like this:

<xsl:choose>
      <xsl:when test="$choosenLanguage &#61; ‘NL’">
        <xsl:variable name="lang.pageTitle" select="Titel in het nederlands'"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:variable name="lang.pageTitle" select="'This is the title in English'"/>
      </xsl:otherwise>
    </xsl:choose>

But I get the error: java.lang.IllegalArgumentException: can't parse argument number $lang.opdracht


回答1:


Here is a complete example how this can be done in a generic way:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my" exclude-result-prefixes="my">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pLang" select="'nl'"/>

 <my:texts>
  <pageTitle lang="en">This is the title in English</pageTitle>
  <pageTitle lang="nl">Titel in het nederlands</pageTitle>
 </my:texts>

 <xsl:variable name="vTexts" select="document('')/*/my:texts"/>

 <xsl:template match="/">
     <html>
      <title>
        <xsl:value-of select="$vTexts/pageTitle[@lang = $pLang]"/>
      </title>
     </html>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on any XML document (not used), the wanted, correct result (the title is generated in accordance with the global/external parameter $pLang) is produced:

<html>
   <title>Titel in het nederlands</title>
</html>

Do note:

It is recommended that all strings be maintained in an XML document that is separate from the XSLT stylesheet file(s). This allows the strings to be modified/added/deleted without changing the XSLT code.

To access the strings from another XML document the code remains almost the same, the only difference is that the argument to the document() function now is the URI to the strings XML document.



来源:https://stackoverflow.com/questions/12086231/how-to-do-i18n-with-xsl-and-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!