2017-10-21 62 views
2

輸入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中。你能幫我們解決這個問題嗎?

回答

2

您可以在這裏使用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')}"> 
+0

謝謝你你的迴應Tim – Sumathi