split XML element into many

后端 未结 1 1066
暖寄归人
暖寄归人 2020-12-20 08:09

this might be impossible, but u guys might have an answer, im tryin to split this xml


    ABSA bank
            


        
相关标签:
1条回答
  • 2020-12-20 08:36

    Try it this way:

    XSLT 1.0

    <xsl:stylesheet version="1.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="*[contains(name(), '.')]" name="nest">
        <xsl:param name="name" select="name()"/>
        <xsl:param name="delimiter" select="'.'"/>
        <xsl:choose>
            <xsl:when test="contains($name, $delimiter)">
                <xsl:element name="{substring-before($name, $delimiter)}" >
                    <!-- recursive call -->
                    <xsl:call-template name="nest">
                        <xsl:with-param name="name" select="substring-after($name, $delimiter)"/>
                    </xsl:call-template>
                </xsl:element>
            </xsl:when>
            <xsl:otherwise>
                <xsl:call-template name="tokenize">
                    <xsl:with-param name="name" select="$name"/>
                    <xsl:with-param name="text" select="."/>
                </xsl:call-template>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    
    <xsl:template name="tokenize">
        <xsl:param name="name"/>
        <xsl:param name="text"/>
        <xsl:param name="delimiter" select="'|'"/>
        <xsl:variable name="token" select="substring-before(concat($text, $delimiter), $delimiter)" />
        <xsl:if test="$token">
            <xsl:element name="{$name}" >
                <xsl:value-of select="$token"/>
            </xsl:element>
        </xsl:if>
        <xsl:if test="contains($text, $delimiter)">
            <!-- recursive call -->
            <xsl:call-template name="tokenize">
                <xsl:with-param name="name" select="$name"/>
                <xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Applied to the following test input:

    XML

    <CTP>
        <name>ABSA bank</name>
        <BAs.BA>bank|sector|issuer</BAs.BA>
        <FAs.FA.F>dep|sec|issue</FAs.FA.F>
    </CTP>
    

    the result will be:

    <?xml version="1.0" encoding="UTF-8"?>
    <CTP>
       <name>ABSA bank</name>
       <BAs>
          <BA>bank</BA>
          <BA>sector</BA>
          <BA>issuer</BA>
       </BAs>
       <FAs>
          <FA>
             <F>dep</F>
             <F>sec</F>
             <F>issue</F>
          </FA>
       </FAs>
    </CTP>
    
    0 讨论(0)
提交回复
热议问题