2012-01-31 86 views
2

我有一些XML像这样:XSLT应用模板和字符串处理

<subsection number="5"> 
     <p> 
     (5) The <link path="123">Secretary of State</link> shall appoint such as.... 
     </p> 
    </subsection> 

我不能改变的XML,我需要剥离出(5)在本段开始,并使用数量属性在父标记创建一个新的段落编号与适当的标记:

<xsl:template match="subsection/p"> 
     <xsl:variable name="number"> 
      <xsl:text>(</xsl:text> 
      <xsl:value-of select="../@number"/> 
      <xsl:text>)</xsl:text> 
     </xsl:variable> 
     <xsl:variable name="copy"> 
      <xsl:value-of select="."/> 
     </xsl:variable> 
     <p> 
      <span class="indent"> 
      <xsl:value-of select="$number" /> 
      </span> 
      <span class="copy"> 
      <xsl:value-of select="substring-after($copy, $number)" /> 
      </span> 
     </p> 
</xsl:template> 

的问题是该段的其余部分可以包含多个XML需要进行改造,如本示例中的链接标记。

我不知道如何使用substring-after函数将模板应用于此。

回答

1

一个明确的方法是将subsection/p元素的第一个文本子元素与所有其他子元素分开处理。为了演示目的,我还添加了一个用于将link元素转换为a元素的模板。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:template match="subsection/p/text()[1]"> 
     <xsl:value-of select="concat('(', ../../@number, ')')"/> 
    </xsl:template> 
    <xsl:template match="subsection/p"> 
     <p> 
      <span class="indent"> 
       <xsl:apply-templates select="text()[1]"/> 
      </span> 
      <span class="copy"> 
       <xsl:apply-templates select="*|text()[not(position()=1)]"/> 
      </span> 
     </p> 
    </xsl:template> 
    <xsl:template match="subsection/p/link"> 
     <a href="{@path}"><xsl:value-of select="."/></a> 
    </xsl:template> 
</xsl:stylesheet> 

该样式产生以下输出:

<p><span class="indent">(5)</span><span class="copy"> 
<a href="123">Secretary of State</a>shall appoint such as....</span></p> 
+0

顶类。非常非常感谢你。 – user888734 2012-01-31 18:25:32