XSLT - 使用正则表达式复制部分属性值
问题描述:
输入XML是像如下所示:XSLT - 使用正则表达式复制部分属性值
<figure>
<subfigure>
<graphic id="c001_f001" position="center" fileref="images/9781626232396_c001_f001.jpg"/>
<legend><para><target/><emph type="bold"><emph type="italic">Fig. 1.1</emph> </emph><emph type="bold">Embryonic development</emph> (after Sadler)</para>
<para>Age in postovulatory days.</para>
</subfigure>
</figure>
输出应该
<figure>
<subfigure id="c001">
<graphic id="c001_f001" position="center" fileref="images/9781626232396_c001_f001.jpg"/>
<legend><para><target/><emph type="bold"><emph type="italic">Fig. 1.1</emph></emph><emph type="bold">Embryonic development</emph> (after Sadler)</para>
<para>Age in postovulatory days.</para>
</subfigure>
</figure>
XSLT:
<xsl:template match="subfigure">
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="graphic/@id"></xsl:value-of>
</xsl:attribute>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
每次属性“id”值是不同的。我们需要将“id”值的第一部分复制并粘贴到子图ID中。你能帮我们解决这个问题吗?
答
您可以在这里使用substring-before
。
<xsl:template match="subfigure">
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="substring-before(graphic/@id, '_')" />
</xsl:attribute>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
或者更好的是,简化模板与Attribute Value Template
<xsl:template match="subfigure">
<subfigure id="{substring-before(graphic/@id, '_')}">
<xsl:apply-templates select="node() | @*"/>
</subfigure>
</xsl:template>
注意,如果你真的想使用正则表达式,你可以使用replace
代替
<subfigure id="{replace(graphic/@id, '(.+)(_.+)', '$1')}">
谢谢你你的回应Tim – Sumathi