我有一个类似于以下xml的xml,
<doc>
<footnote>
<p type="Foot">
<link ref="http://www.facebook.com"/>
<c>content</c>
<d>cnotent</d>
</p>
<p type="Foot">
<link ref="http://www.google.com"/>
<c>content</c>
<d>cnotent</d>
</p>
</footnote>
</doc>我的要求是,
1)向具有属性<p>的type="Foot"节点添加动态id。
2)在<newNode>节点中添加名为<p>的新节点
3)向<newNode>添加动态id
所以输出应该是
<doc>
<footnote>
<p id="ref-1" type="Foot">
<newNode type="direct" refId="foot-1"/>
<link ref="http://www.facebook.com"/>
<c>content</c>
<d>cntent</d>
</p>
<p id="ref-2" type="Foot">
<newNode type="direct" refId="foot-2"/>
<link ref="http://www.google.com"/>
<c>content</c>
<d>cotent</d>
</p>
</footnote>
</doc>我在xsl之后写了这样的文章
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<!-- add new dynamic attribute to <p> -->
<xsl:template match="p[@type='Foot']">
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="'ref-'"/>
<xsl:number count="p[@type='Foot']" level="any"/>
</xsl:attribute>
<xsl:apply-templates select="@*|node()" />
<!-- add new node with dynamic attribute -->
<newNode type="direct">
<xsl:attribute name="refId">
<xsl:value-of select="'foot-'"/>
<xsl:number count="p[@type='Foot']" level="any"></xsl:number>
</xsl:attribute>
</newNode>
</xsl:copy>
</xsl:template>我的问题是在<p>节点中添加新节点和最后一个节点(如下面所示),我需要在<p>节点中添加作为第一个节点。
<p id="ref-1" type="Foot">
<link ref="http://www.facebook.com"/>
<c>content</c>
<d>cntent</d>
<newNode type="direct" refId="foot-1"/>
</p>如何在<p>节点中放置第一个节点,如下所示?
<p id="ref-1" type="Foot">
<newNode type="direct" refId="foot-1"/>
<link ref="http://www.facebook.com"/>
<c>content</c>
<d>cntent</d>
</p>发布于 2015-07-24 07:56:23
您需要确保在创建新节点后复制子元素:
<xsl:template match="p[@type='Foot']">
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="'ref-'"/>
<xsl:number count="p[@type='Foot']" level="any"/>
</xsl:attribute>
<xsl:apply-templates select="@*" />
<!-- add new node with dynamic attribute -->
<newNode type="direct">
<xsl:attribute name="refId">
<xsl:value-of select="'foot-'"/>
<xsl:number count="p[@type='Foot']" level="any"></xsl:number>
</xsl:attribute>
</newNode>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>https://stackoverflow.com/questions/31604992
复制相似问题