获取变量的值到另一个模板

时间:2016-11-28 01:30:57

标签: xslt xslt-1.0 xslt-2.0

我在互联网上找到了关于将变量传递给其他模板的参考资料。我试图遵循所有引用,但是,我无法获得我需要填充的值。我有这个xml文件:

<Item>
   <Test>
      <ID>123345677</ID>
   </Test>
   <DisplayID>99884534</DisplayID>
</Item>

如果DisplayID不为null,我需要填充MsgId元素,否则从ID获取值。我的XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="ID">
    <xsl:variable name="IDV" select="substring(.,0,35)"/>
    <xsl:apply-templates select="DisplayID">
        <xsl:with-param name="IDP" select="$IDV"/>
    </xsl:apply-templates>
</xsl:template>
<xsl:template match="DisplayID">
    <xsl:param name="IDP"/>
    <xsl:element name="MsgId">
        <xsl:choose>
            <xsl:when test=".!='' or ./*">
                <xsl:value-of select="substring(.,0,35)"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="substring($IDP,0,35)"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:element>
</xsl:template>

如果DisplayID不为null,则该条件有效,但是,如果我删除了DisplayID的值,则ID中没有值。我不知道我是否正确地做到了。

非常感谢您的反馈。

2 个答案:

答案 0 :(得分:0)

请试试这个,

参考演示:http://xsltransform.net/ejivdHb/16

function n(stringNum){
   // some code that I don't want to write right now.
}

var fooBar = n("1,000,000");
// fooBar = 1000000

答案 1 :(得分:0)

由于这是标记的XSLT 2.0,@ TechBreak的match =“Item”模板可以替换为

<xsl:template match="Item">
    <MsgId>
        <xsl:value-of select="substring(
            if (DisplayId != '') 
            then DisplayID 
            else Test/ID, 1 ,35)"/>
    </MsgId>
</xsl:template>

(注意字符计数从1开始)

相关问题