XSLT - 向现有节点添加属性和新节点
XSLT - add attribute and new node to existing node
我需要向现有节点添加属性和新节点
示例:
<doc>
<a></a>
<a></a>
<a></a>
<d></d>
<a></a>
<f></f>
</doc>
我现在需要的是将属性添加到 <a>
节点并在节点内添加新节点。
所以输出是,
<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>
这段代码按预期添加了新属性和新节点,但问题是它只添加到第一个节点,并且在 oxygen 编辑器中出现此消息和以下五个消息后无法编译。 ' An attribute node (id) cannot be created after a child of the containing element.
我该如何解决这个问题?
您是对的,但是您需要确保所有子节点都添加在任何属性之后。必须先添加属性,然后再添加任何子节点。
试试这个模板
<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>
我需要向现有节点添加属性和新节点
示例:
<doc>
<a></a>
<a></a>
<a></a>
<d></d>
<a></a>
<f></f>
</doc>
我现在需要的是将属性添加到 <a>
节点并在节点内添加新节点。
所以输出是,
<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>
这段代码按预期添加了新属性和新节点,但问题是它只添加到第一个节点,并且在 oxygen 编辑器中出现此消息和以下五个消息后无法编译。 ' An attribute node (id) cannot be created after a child of the containing element.
我该如何解决这个问题?
您是对的,但是您需要确保所有子节点都添加在任何属性之后。必须先添加属性,然后再添加任何子节点。
试试这个模板
<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>