Using XSLT to translate an XML file

前端 未结 1 1285
傲寒
傲寒 2020-12-18 05:45

I want to translate a given XML file (it is a RelaxNG grammar) to other languages via XSLT. Suppose the XML file is:



        
相关标签:
1条回答
  • 2020-12-18 06:26

    This transformation:

    <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="pFrom" select="'en'"/>
     <xsl:param name="pTo" select="'de'"/>
    
     <xsl:key name="kIdByLangVal" match="@dId"
      use="concat(../../@lang, '+', ../@value)"/>
    
     <xsl:key name="kValByLangId" match="@value"
      use="concat(../../@lang, '+', ../@dId)"/>
    
     <xsl:variable name="vDicts" select=
      "document('file:///c:/temp/delete/dicts.xml')"/>
    
     <xsl:template match="node()|@*">
      <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
     </xsl:template>
    
     <xsl:template match="@name">
      <xsl:variable name="vCur" select="."/>
    
      <xsl:attribute name="name">
       <xsl:for-each select="$vDicts">
        <xsl:value-of select=
         "key('kValByLangId',
              concat($pTo, '+',
                    key('kIdByLangVal',
                        concat($pFrom, '+', $vCur)
                       )
                     )
            )
         "/>
       </xsl:for-each>
      </xsl:attribute>
     </xsl:template>
    </xsl:stylesheet>
    

    when applied on the provided XML document:

    <grammar>
        <element name="table" />
        <element name="chair" />
    </grammar>
    

    and having the file C:\temp\delete\dicts.xml as:

    <dictionaries>
     <dictionary lang="en">
      <word dId="1" value="table"/>
      <word dId="2" value="chair"/>
     </dictionary>
     <dictionary lang="de">
      <word dId="1" value="Tisch"/>
      <word dId="2" value="Stuhl"/>
     </dictionary>
    </dictionaries>
    

    produces the wanted, correct result:

    <grammar>
       <element name="Tisch"/>
       <element name="Stuhl"/>
    </grammar>
    
    0 讨论(0)
提交回复
热议问题