Search code examples
xmlxsltxslt-grouping

how to extract partial value from an element and assign as attribute to another element


I am working on XML to XML transformations through XSLT.

I want to extract aprtial value from an element and assign that as attribute to new element.

Source XML:

      <content>
        <component>
      <aaa>HI
           <strong>[a_b_c]</strong>
              : More Information Needed
            <strong>[d_e_f]</strong>XXX
      </aaa>
     </component>
     <content>

Target XML:

    <ddd>hi<dv name='a_b_c'/>: More Information Needed <dv name='d_e_f'/> XXX

    </ddd>

can any one suggest how to do it through XSLT.

Thank you in advance.


Solution

  • XSLT 1.0

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output indent="yes"/>
      <xsl:strip-space elements="*"/>
    
      <xsl:template match="aaa">
        <ddd>
          <xsl:value-of select="substring-before(.,'[')"/>
          <dv name="{substring-before(substring-after(.,'['),']')}"/>
        </ddd>
      </xsl:template>
    
    </xsl:stylesheet>
    

    or

    XSLT 2.0

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output indent="yes"/>
      <xsl:strip-space elements="*"/>
    
      <xsl:template match="aaa">
        <ddd>
          <xsl:value-of select="tokenize(.,'\[')[1]"/>
          <dv name="{tokenize(tokenize(.,'\[')[2],'\]')[1]}"/>
        </ddd>
      </xsl:template>
    
    </xsl:stylesheet>
    

    EDIT

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output indent="yes"/>
      <xsl:strip-space elements="*"/>
    
      <xsl:template match="node()|@*">
        <xsl:copy>
          <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="aaa">
        <ddd>
          <xsl:apply-templates select="node()|@*"/>
        </ddd>
      </xsl:template>
    
      <xsl:template match="content|component">
        <xsl:apply-templates/>
      </xsl:template>
    
      <xsl:template match="strong">
        <dv name="{normalize-space(.)}"/>
      </xsl:template>
    
    </xsl:stylesheet>