我想使用 XSLT 做一些简单的事情(或者我认为)。我想将一个元素列表拆分为两个,使用重命名一个元素的想法是这样形成的 xml:
<elem at="value" id="something"/>
<elem at="value" id="something2"/>
<elem at="random" id="something3"/>
Run Code Online (Sandbox Code Playgroud)
将转换为:
<elemVal id="something"/>
<elemVal id="something2"/>
<elemRa id="something3"/>
Run Code Online (Sandbox Code Playgroud)
(新元素名称是静态的)因此元素根据属性的值进行重命名。
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="elem/@at[.='value']">
<xsl:element name="elemVa">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有一个身份模板,但我不明白如何倒退并更改元素名称,保留其内容。
代替
<xsl:template match="elem/@at[.='value']">
Run Code Online (Sandbox Code Playgroud)
你需要
<xsl:template match="elem[@at ='value']">
Run Code Online (Sandbox Code Playgroud)
然后创建新元素(文字就足够了)并确保at不处理该属性:
<xsl:template match="elem[@at ='value']">
<elemVa>
<xsl:apply-templates select="@* except @at | node()"/>
</elemVa>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
以上是XSLT/XPath 2.0,在1.0中可以使用
<xsl:template match="elem[@at ='value']">
<elemVa>
<xsl:apply-templates select="@*[not(local-name() = 'at')] | node()"/>
</elemVa>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)