具有多个嵌套对象的字段上的XSLT

时间:2017-04-28 18:34:44

标签: xml api xslt soa

我正在为我目前的项目学习XSLT而且遇到了一个问题,是否有人可以帮助我实现这种转变?

INPUT:

<response>
<num>5521187659301</num>
<object>1,20170109,20170504,14000.00|3,20170112,20170409,50000.00|4,19800229,20170422,2000000.00|</object>
</response>

输出:

<response>
    <num>5521187659301</num>
    <object>
        <object-child>
            <param1>1</param1>
            <param2>20170109</param2>
            <param3>20170504</param3>
            <param4>14000.00</param4>
        </object-child>
        <object-child>
            <param1>3</param1>
            <param2>20170112</param2>
            <param3>20170409</param3>
            <param4>50000.00</param4>
        </object-child>
        <object-child>
            <param1>4</param1>
            <param2>19800229</param2>
            <param3>20170422</param3>
            <param4>2000000.00</param4>
        </object-child>
    </object>
</response>

到目前为止我处于现阶段

<xsl:template match="/">
    <response>
    <num><xsl:value-of select="response/num"/></num>
    <object>
        <xsl:for-each select="response/object">
            <xsl:for-each select="tokenize(.,'|')">
                <object-child>                      

                </object-child>
            </xsl:for-each>
        </xsl:for-each>
     </object>
   </response>
 </xsl:template>

1 个答案:

答案 0 :(得分:0)

显然,你需要两次标记:一次在外|分隔符上(注意它需要被转义),然后在内部逗号上。

以这种方式尝试:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="object">
     <xsl:copy>
        <xsl:for-each select="tokenize(., '\|')">
            <object-child>  
                <xsl:for-each select="tokenize(., ',')">
                    <xsl:element name="param{position()}">
                        <xsl:value-of select="."/>
                    </xsl:element>
                </xsl:for-each>
            </object-child>
        </xsl:for-each>
    </xsl:copy>   
</xsl:template>

</xsl:stylesheet>

演示:http://xsltransform.net/gVhD8QE