2017-02-14 54 views
0

我在关键函数中有一个问题,关键函数没有在下面的代码中运行。XSL:KEY外部文件的功能

我输入

XML(Keys.xml)

<?xml version="1.0" encoding="UTF-8"?> 
<Keys> 
    <Key year="2001" name="ABC"/> 
    <Key year="2002" name="BCA"/> 
</Keys> 

XML转换

<?xml version="1.0" encoding="UTF-8"?> 
<p> 
    <text> .. .. <key>ABC</key> ...</text> 
    <text> .. .. <key>BCA</key> ...</text> 
</p> 

XSLT

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="2.0"> 
    <xsl:template match="node()|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:key name="keydata" match="*[name() = document('keys.xml')]/Keys/Key" use="@name"/> 
    <xsl:template match="key"> 
     <xsl:copy> 
      <xsl:attribute name="ref"><xsl:value-of select="key('keydata', .)/@year"/></xsl:attribute> 
      <xsl:value-of select="."/> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

输出

<p> 
    <text> .. .. <key ref="">ABC</key> ...</text> 
    <text> .. .. <key ref="">BCA</key> ...</text> 
</p> 

希望的输出继电器

<p> 
    <text> .. .. <key ref="2001">ABC</key> ...</text> 
    <text> .. .. <key ref="2002">BCA</key> ...</text> 
</p> 
+0

这样的谓词'[名称()=文件( 'keys.xml')]'似乎并不正确。你有错误信息吗? – potame

+0

不,没有错误信息 – Rupesh

回答

1

这应该工作:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="2.0"> 

    <xsl:variable name="keys" select="document('keys.xml')" as="document-node()"/> 

    <xsl:key name="keydata" match="Key" use="@name"/> 

    <xsl:template match="node()|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="key"> 
     <xsl:copy> 
      <xsl:attribute name="ref"><xsl:value-of select="$keys/key('keydata', current())/@year"/></xsl:attribute> 
      <xsl:value-of select="."/> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

在XSL规范中,有一个名为例如“Example: Using Keys to Reference other Documents”恰好你的使用情况相符。

这是所得到的文档:

<?xml version="1.0" encoding="UTF-8"?> 
<p> 
    <text> .. .. <key ref="2001">ABC</key> ...</text> 
    <text> .. .. <key ref="2002">BCA</key> ...</text> 
</p> 
+0

谢谢,它现在工作 – Rupesh

1

变化<xsl:key name="keydata" match="*[name() = document('keys.xml')]/Keys/Key" use="@name"/><xsl:key name="keydata" match="Keys/Key" use="@name"/>然后<xsl:attribute name="ref"><xsl:value-of select="key('keydata', .)/@year"/></xsl:attribute><xsl:attribute name="ref" select="key('keydata', . doc('Keys.xml'))/@year"/></xsl:attribute>

+0

感谢您的帮助 – Rupesh