2012-01-31 35 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