输入xml就像,
<figure id="c035_f001" counter="yes">
<legend><para>The TLIF is indicated to aid reduction of spondylolisthesis and restore disc height, which decompresses the foramina.</para></legend>
<subfigure>
<graphic position="center" fileref="images/9781626230408_c035_f001.jpg"/>
</subfigure>
<subfigure>
<graphic position="center" fileref="images/9781626230408_c035_f001a.jpg"/>
</subfigure>
</figure>输出应该是,
<figure counter="yes">
<legend><para>The TLIF is indicated to aid reduction of spondylolisthesis and restore disc height, which decompresses the foramina.</para></legend>
<subfigure id="c035_f001">
<graphic position="center" fileref="images/9781626230408_c035_f001.jpg"/>
</subfigure>
<subfigure>
<graphic position="center" fileref="images/9781626230408_c035_f001a.jpg"/>
</subfigure>
</figure>我们编写了如下所示的XSLT。
<xsl:template match="subfigure">
<xsl:variable name="fig" select="parent::figure/@id"></xsl:variable>
<xsl:choose>
<xsl:when test="subfigure[not[@id]]">
<xsl:if test="subfigure[not[@id]]">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="id">
<xsl:value-of select="$fig"></xsl:value-of>
</xsl:attribute>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:if>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>在使用上面的xslt时,我们得到的输出是,
<figure counter="yes">
<legend><para>The TLIF is indicated to aid reduction of spondylolisthesis and restore disc height, which decompresses the foramina.</para></legend>
<subfigure id="c035_f001">
<graphic position="center" fileref="images/9781626230408_c035_f001.jpg"/>
</subfigure>
<subfigure id="c035_f001">
<graphic position="center" fileref="images/9781626230408_c035_f001a.jpg"/>
</subfigure>
</figure>在两个“子图”元素上重复的"id“。但我们只需要第一位置。你能指引我们吗。
发布于 2017-10-25 13:27:39
考虑将一般身份转换移动到自己的模板中:
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>然后为需要特殊处理的节点添加模板,确保将所有条件都放在匹配模式中。
<xsl:template match="figure[@id]/subfigure[1][not(@id)]">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:copy-of select="../@id"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>发布于 2017-10-25 13:28:20
一些初赛:
(1)所提供的XSLT不产生演示的XML输出,而只生成两个<subfigure>元素。
(2) not[]指的是一个元素<not>,但实际上您的意思是否定参数的not()。
(3)我知道您需要将@id从<figure>“移动”到<subfigure>。其他的一切都保持原样,对吗?
(4)要完成这项任务,您只需要一个身份副本,但有一些例外:
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<!-- remove @id from figure (but only when it contains subfigures) -->
<xsl:template match="figure[subfigure]/@id"/>
<!-- insert @id into first subfigure from superordinate figure -->
<xsl:template match="subfigure[not(@id)][1]">
<subfigure>
<xsl:copy-of select="ancestor::figure[1]/@id"/>
<!-- do not forget to copy possible other attributes -->
<xsl:apply-templates select="@* | node()"/>
</subfigure>
</xsl:template>希望能帮上忙!
https://stackoverflow.com/questions/46932795
复制相似问题