考虑以下XSLT
<div class="name-input">
<xsl:attribute name="class">mandatory</xsl:attribute>
<xsl:copy-of select="FIRSTNAME/*/input"/>
</div>
生成此标记
<div class="pax-mandatory-field">
<input type="text" id="FirstName" />
</div>
我想要的是
<div class="name-input">
<input type="text" id="FirstName" class="mandatory" />
</div>
我尝试了这个(它没有工作)
<div class="name-input">
<xsl:copy-of select="FIRSTNAME/*/input">
<xsl:attribute name="class">mandatory</xsl:attribute>
</xsl:copy-of>
</div>
甚至不确定从哪里开始。有什么需要改变的想法吗?
答案 0 :(得分:3)
假设您输入了以下内容:
<FIRSTNAME>
<ANYNODE>
<input type="text" id="FirstName" />
</ANYNODE>
</FIRSTNAME>
首先使用身份模板
开始 <xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
从上面的示例XML中,为input
<xsl:template match="FIRSTNAME/*/input">
<!-- set container tags -->
<div class="name-input">
<!-- xsl:copy here copies the current node -->
<xsl:copy>
<!-- applies the attributes if present -->
<xsl:apply-templates select="@*"/>
<!-- sets the class attribute -->
<xsl:attribute name="class">mandatory</xsl:attribute>
</xsl:copy>
</div>
</xsl:template>
因此XSL:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="FIRSTNAME/*/input">
<div class="name-input">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="class">mandatory</xsl:attribute>
</xsl:copy>
</div>
</xsl:template>
</xsl:stylesheet>
的产率:
<FIRSTNAME>
<ANYNODE>
<div class="name-input">
<input type="text" id="FirstName" class="mandatory"/>
</div>
</ANYNODE>
</FIRSTNAME>
答案 1 :(得分:0)
如果您需要更改/添加输入的属性,则需要将表单copy-of
切换为apply-templates。例如:
为&#34;特殊&#34;设置新模板输入元素处理的模式,以避免其他输入元素的副作用。
<xsl:template match="input" mode="myfirst">
<xsl:copy>
<xsl:copy-of select="@*" />
<xsl:attribute name="class">mandatory</xsl:attribute>
<xsl:apply-templates select="*" />
</xsl:copy>
</xsl:template>
而不是使用它:
<div class="name-input">
<xsl:apply-templates select="FIRSTNAME/*/input" mode="myfirst" />
</div>