我有XML:
<doc>
<p id="123" sec="abc"></p>
</doc>
Run Code Online (Sandbox Code Playgroud)
使用XSLT,我需要:
1)添加name带有值的新属性'myname'
2)复制相同的sec值
3)id将属性覆盖为新值
我写了以下XSLT来做到这一点,
<xsl:template match="p">
<p name="myname" id="999">
<xsl:apply-templates select="node()|@*"/>
</p>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
它给了我以下结果:
<doc>
<p name="myname" id="123" sec="abc"></p>
</doc>
Run Code Online (Sandbox Code Playgroud)
期望的结果是:
<doc>
<p name="myname" id="999" sec="abc"></p>
</doc>
Run Code Online (Sandbox Code Playgroud)
它似乎不会覆盖id属性值.如何从XSLT覆盖此值?
更改模板
<xsl:template match="p">
<p name="myname" id="999">
<xsl:apply-templates select="node()|@*"/>
</p>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
至
<xsl:template match="p">
<p name="myname" id="999">
<xsl:apply-templates select="@* except @id, node()"/>
</p>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
或者为id属性写一个模板:
<xsl:template match="p">
<p name="myname">
<xsl:apply-templates select="@* , node()"/>
</p>
</xsl:template>
<xsl:template match="p/@id">
<xsl:attribute name="id" select="999"/>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)