[英]How to call template from another template in XSLT?
我有以下xml:
<rootelement>
<parentelement>
<mytype>123</mytype>
<myvalue>abc</myvalue>
</parentelement>
<parentelement>
<mytype>234</mytype>
<myvalue>xyz</myvalue>
</parentelement>
</rootelement>
首先,我使用模板使用字典来更改mytype的值:
<parentelement>
<mytype>Mapped1</mytype>
<myvalue>abc</myvalue>
</parentelement>
<parentelement>
<myvalue>qwe</myvalue>
</parentelement>
我想应用下一个转换,如果mytype标记已删除,则该转换将删除整个父元素。 换句话说,我希望第二个转换创建以下XML:
<parentelement>
<mytype>Mapped1</mytype>
<myvalue>abc</myvalue>
</parentelement>
我尝试在第一个模板的末尾添加以下内容:
<xsl:template match="mytype">
...
<xsl:call-template name="mytypetemplate"/>
</xsl:template>
以下面的模板为第二个模板:
<xsl:template name="mytypetemplate" match="/rootelement/parentelement[not(mytype) or mytype[not(node())]]"/>
但是我得到的结果是它执行了第一个模板,而不是第二个。 换句话说,它将删除mytype(第一个模板),但不会删除没有mytype的元素的整个父元素(第二个模板)。 如何在第一个转换之后应用第二个转换?
谢谢!
在示例中,您可以使用mode
s( https://www.w3.org/TR/xslt/#element-mode )分隔处理步骤,并使用变量存储和使用临时结果。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:mode name="step1" on-no-match="shallow-copy"/>
<xsl:variable name="step1-result">
<xsl:apply-templates mode="step1"/>
</xsl:variable>
<xsl:template match="parentelement[myvalue = 'abc']/mytype" mode="step1"/>
<xsl:template match="/">
<xsl:apply-templates select="$step1-result/node()"/>
</xsl:template>
<xsl:template match="parentelement[not(mytype)]"/>
</xsl:stylesheet>
模式step1
除去mytype
从元件parentelement
以s myvalue
存在abc
和默认模式处理在变量创建的临时结果step1-result
以消除任何parentelement
不是具有mytype
孩子。
所以对于输入
<?xml version="1.0" encoding="UTF-8"?>
<rootelement>
<parentelement>
<mytype>123</mytype>
<myvalue>abc</myvalue>
</parentelement>
<parentelement>
<mytype>234</mytype>
<myvalue>xyz</myvalue>
</parentelement>
</rootelement>
那么结果是
<rootelement>
<parentelement>
<mytype>234</mytype>
<myvalue>xyz</myvalue>
</parentelement>
</rootelement>
在线http://xsltfiddle.liberty-development.net/b4GWV2 。
略有变化是
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:mode name="step1" on-no-match="shallow-copy"/>
<xsl:template match="parentelement[myvalue = 'abc']/mytype" mode="step1"/>
<xsl:template match="/">
<xsl:variable name="step1-result">
<xsl:apply-templates mode="step1"/>
</xsl:variable>
<xsl:apply-templates select="$step1-result/node()"/>
</xsl:template>
<xsl:template match="parentelement[not(mytype)]"/>
</xsl:stylesheet>
您可以在http://xsltfiddle.liberty-development.net/b4GWV2/1上在线查看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.