2017-02-11 86 views
0

我在访问XSLT中的变量时遇到问题。
我只是定义VAR这样的:使用Xsl变量

<xsl:variable name="myName" select="@owner"/> 

当我使用此代码它不工作:

<title>{$myName}</title> 

但此代码的工作:

<title><xsl:value-of select="$myName"/></title> 

我想比较上面的变量实体中的XML 当值实体等于MYNAME我显示一些代码否则另一个码显示

<xsl:for-each select="message"> 
    <xsl:choose> 
     <xsl:when test="from = $myName"> 
      ... 
     </xsl:when> 
     <xsl:otherwise> 
      ... 
     </xsl:otherwise> 
    </xsl:choose> 
</xsl:for-each> 

XML文件包含这样的信息:

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="history.xsl"?> 
<history xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:noNamespaceSchemaLocation="history.xsd" owner="Mike"> 

<message> 
    <from>Mike</from> 
    <to>Gem</to> 
    <date>2002-09-24</date> 
    <color>red</color> 
    <size>20</size> 
    <family>cursive</family> 
    <style>overline</style> 
    <body>welcome</body> 
</message> 
</history> 
+1

您需要提供相关的XML输入和预期的XML输出,以便我们更好的锻炼问题。看起来你想'test =“@ from = $ myName”'(介意“@”) – programaths

+0

你在变量中引用的“owner”属性在哪里? – programaths

+0

你想试试这个:http://xsltransform.net/bwdwsD? – programaths

回答

0

下面是一个XSLT:

<?xml version="1.0" encoding="UTF-8" ?> 
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> 
    <xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" /> 
    <xsl:variable name="myName" select="/history/@owner"/> 

    <xsl:template match="/"> 

     <xsl:apply-templates/> 

    </xsl:template> 

    <xsl:template match="message"> 
     <xsl:choose> 
     <xsl:when test="from = $myName"> 
      Mike message 
     </xsl:when> 
     <xsl:otherwise> 
      Other message 
     </xsl:otherwise> 
    </xsl:choose>   
    </xsl:template> 
</xsl:transform> 

它将在执行开始时拉取值并将其放入“myName”变量中。

然后,我匹配标签名称(消息)并使用XSL选择,就像您一样。

您还可以避免使用xsl:这样做选择:

<?xml version="1.0" encoding="UTF-8" ?> 
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> 
    <xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" /> 
    <xsl:variable name="myName" select="/history/@owner"/> 

    <xsl:template match="/"> 

     <xsl:apply-templates/> 

    </xsl:template> 

    <xsl:template match="message[from=$myName]">   
      Mike message     
    </xsl:template> 

    <xsl:template match="message">   
      Other message     
    </xsl:template> 
</xsl:transform> 

这说明你的东西很重要:XSL挑选第一个匹配的模板!

第二个选项更适合模块化。第一个暗示嵌套。这一秒不!

测试都在线: