Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

xml - XSLT - split string on every nth character in loop

in one of our requirement we are receiving a string of n character and at provider at we we sending that to SAP. Due to some limitation at target end, we need to check for string that if its more then 100 char, we need to split that and send to target application in 2 different segment(same name) like

input - This is a test message......(till 150 char)

in XSLT transformation -we need to split it like

<text>first 100 char<text>
<text> 101 to 200 char<text>
...

Since number of character is not predefined so I cant use substring function here. This should be as a part of loop..

Could someone pls help here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In XSLT 2.0, you could do something like this:

Example simplified to splitting the input into tokens of (up to) 6 characters each.

XML

<input>abcde1abcde2abcde3abcde4abcde5abcde6abcde7abcde8abc</input>

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:template match="/">
     <output>
        <xsl:variable name="string" select="input" />
        <xsl:for-each select="0 to (string-length($string) - 1) idiv 6">
            <token>
                <xsl:value-of select="substring($string, . * 6 + 1, 6)" />
            </token>
        </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>

Result

<output>
   <token>abcde1</token>
   <token>abcde2</token>
   <token>abcde3</token>
   <token>abcde4</token>
   <token>abcde5</token>
   <token>abcde6</token>
   <token>abcde7</token>
   <token>abcde8</token>
   <token>abc</token>
</output>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...