xsltinvisible-xml

Split element within xslt file


I have the following input

UK/006/10
US/004/12

And wanted to get the following output.

Country: UK
Code:006
Line: 10

Country: US
Code:004
Line:12

I tried to use following, but I need something simple, like split function. Can someone help on this?

<xsl:value-of select="substring-before(substring-after($User_def_type_4, '/'), '/')" />

Solution

  • Using Invisible XML, you could define a grammar for your text data to map it to XML, then an extension function library like the CoffeeSacks library to Saxon Java can be used in XSLT to parse and post-process the text so that with e.g. the XML input being

    <data>UK/006/10
    US/004/12</data>
    

    and the XSLT being

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      version="3.0"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:cs="http://nineml.com/ns/coffeesacks"
      exclude-result-prefixes="#all"
      expand-text="yes">
      
      <xsl:template match="data">
        <xsl:apply-templates select="cs:parse-string(cs:grammar-string($grammar), .)/node()"/>
      </xsl:template>
          
      <xsl:output method="xml" indent="yes"/>
    
      <xsl:mode on-no-match="shallow-copy"/>
    
      <xsl:template match="/" name="xsl:initial-template">
        <xsl:next-match/>
        <xsl:comment xmlns:saxon="http://saxon.sf.net/">Run with {system-property('xsl:product-name')} {system-property('xsl:product-version')} {system-property('Q{http://saxon.sf.net/}platform')}</xsl:comment>
      </xsl:template>
    
      <xsl:param name="grammar" as="xs:string" expand-text="no">Countries = Country*.
    Country = Name, -'/', Code, -'/', Line, #A?.
    Name = ['A'-'Z'],['A'-'Z'].
    Code = ['0'-'9'],['0'-'9'],['0'-'9'].
    Line = ['0'-'9'],['0'-'9'].</xsl:param>
    
    </xsl:stylesheet>
    

    you get e.g.

    <?xml version="1.0" encoding="UTF-8"?>
    <Countries>
       <Country>
          <Name>UK</Name>
          <Code>006</Code>
          <Line>10</Line>
       </Country>
       <Country>
          <Name>US</Name>
          <Code>004</Code>
          <Line>12</Line>
       </Country>
    </Countries>
    <!--Run with SAXON HE 11.3 --> 
    

    Online sample using Saxon HE 11 Java and the named CoffeeSacks library.