我需要将属性和新节点添加到现有节点
示例:
<doc>
<a></a>
<a></a>
<a></a>
<d></d>
<a></a>
<f></f>
</doc>
我需要的是现在添加到<a>
节点的attrinute并在节点内添加新节点。
所以输出就是,
<doc>
<a id='myId'> <new_node attr="myattr"/> </a>
<a id='myId'> <new_node attr="myattr"/> </a>
<a id='myId'> <new_node attr="myattr"/> </a>
<d></d>
<a id='myId'> <new_node attr="myattr"/> </a>
<f></f>
</doc>
我写了以下代码来完成这项任务,
<xsl:template match="a">
<xsl:apply-templates select="@*|node()"/>
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="'myId'"/>
</xsl:attribute>
</xsl:copy>
<new_node>
<xsl:attribute name="attr">
<xsl:value-of select="'myattr'"/>
</xsl:attribute>
</new_node>
</xsl:template>
此代码按预期添加了新属性和新节点,但问题是它只添加到第一个节点,并且在此编辑器之后不会编译,并且在氧编辑器中不会编译以下五个消息。 ' An attribute node (id) cannot be created after a child of the containing element.
我该如何解决这个问题?
答案 0 :(得分:1)
您使用的是正确的行,但您需要确保在任何属性之后添加任何子节点。必须首先在任何子节点之前添加属性。
试试这个模板
<xsl:template match="a">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="id">
<xsl:value-of select="'myId'"/>
</xsl:attribute>
<xsl:apply-templates select="node()"/>
<new_node>
<xsl:attribute name="attr">
<xsl:value-of select="'myattr'"/>
</xsl:attribute>
</new_node>
</xsl:copy>
</xsl:template>
实际上,您可以稍微简化一下,直接写出属性。试试这个
<xsl:template match="a">
<a id="myId">
<xsl:apply-templates select="@*|node()"/>
<new_node attr="myattr" />
</a>
</xsl:template>