2011-04-22 41 views
2

我正在處理一個並不真正支持子元素的數據庫。爲了解決這個問題,我們在一串值中使用了波形括號}}來指示子元素之間的分隔。當我們出口到XML,它看起來是這樣的:XSLT:如何將刪除的值分隔成獨特的元素

<geographicSubject> 
    <data>Mexico }} tgn }} 123456</data> 
    <data>Mexico City }} tgn }} 7891011</data> 
    <data>Main Street }} tgn }} 654321</data> 
</geographicSubject> 

我的問題:如何創建我們的XSLT,這樣它將該字符串<data>成單獨的唯一命名的子單元是這樣的:

<data> 
    <location>Mexico</location> 
    <source>tgn</source> 
    <id>123456</id> 
</data> 

第一個}}表示「源」的開始,第二個}}表示「id」的開始。感謝任何人願意幫助!

回答

4

撰寫的標記生成器:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:e="http://localhost"> 
    <e:e>location</e:e> 
    <e:e>source</e:e> 
    <e:e>id</e:e> 
    <xsl:variable name="vElement" select="document('')/*/e:*"/> 
    <xsl:template match="node()|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="data/text()" name="tokenizer"> 
     <xsl:param name="pString" select="string()"/> 
     <xsl:param name="pPosition" select="1"/> 
     <xsl:if test="$pString"> 
      <xsl:element name="{$vElement[$pPosition]}"> 
       <xsl:value-of 
       select="normalize-space(
          substring-before(concat($pString,'}}'),'}}') 
         )"/> 
      </xsl:element> 
      <xsl:call-template name="tokenizer"> 
       <xsl:with-param name="pString" 
           select="substring-after($pString,'}}')"/> 
       <xsl:with-param name="pPosition" select="$pPosition + 1"/> 
      </xsl:call-template> 
     </xsl:if> 
    </xsl:template> 
</xsl:stylesheet> 

輸出:

<geographicSubject> 
    <data> 
     <location>Mexico</location> 
     <source>tgn</source> 
     <id>123456</id> 
    </data> 
    <data> 
     <location>Mexico City</location> 
     <source>tgn</source> 
     <id>7891011</id> 
    </data> 
    <data> 
     <location>Main Street</location> 
     <source>tgn</source> 
     <id>654321</id> 
    </data> 
</geographicSubject> 
+2

的通過位置動態地選擇正確的元素名稱 – 2011-04-22 15:54:20

+0

感謝您的回答,亞歷尼斯方法。我還沒有試過,但謝謝! – 2011-04-22 20:08:32

+0

@s。 nakasone:不客氣。 – 2011-04-22 22:59:41