Sahal
Sahal

Reputation: 4136

Create a XSLT variable concatenating unique child element values

Here is my XML

<?xml version='1.0'?>
<root>
    <elems>
        <status>Completed</status>
        <description>Records</description>
        <sub_type>SEC</sub_type>
        <type>FIR</type>
        <result>Done</result>
    </elems>
    <elems>
        <status>Completed</status>
        <description>Records</description>
        <sub_type>SEC</sub_type>
        <type>FIR</type>
        <result>Done</result>
    </elems>
    <elems>
        <status>Completed</status>
        <description>Morals</description>
        <sub_type>GIX</sub_type>
        <type>PANC</type>
        <result>Done</result>
    </elems>
    <elems>
        <status>Completed</status>
        <description>Morals</description>
        <sub_type>GIX</sub_type>
        <type>PANC</type>
        <result>Done</result>
    </elems>
    <elems>
        <status>Completed</status>
        <description>Checking</description>
        <type>SSO</type>
        <result>Done</result>
    </elems>
</root>

I want one variable and it should give the unique values (as elems elements are repeating and duplicate elements) like below by concatenating type and sub_type elements. sub_type can be null element. Variable name can be vars for my below example..

FIRSEC PANCGIX SSO 

And then I should be able to foreach using this $var

<root>
   <xsl:for-each select="$vars">
       <inner><xsl:value-of select="." /></inner>
    </xsl:for-each>
<root>

And it should print

<root>
   <inner>FIRSEC</inner>
   <inner>PANCGIX</inner>
   <inner>SSO</inner>
</root>

Upvotes: 0

Views: 67

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116982

In XSLT 2.0 this is rather trivial using the distinct-values() function:

<xsl:variable name="vars" select="distinct-values(/root/elems/concat(type,sub_type))"/>

Note that the variable is redundant, since you can do directly:

<root>
   <xsl:for-each select="distinct-values(/root/elems/concat(type,sub_type))">
       <inner>
           <xsl:value-of select="." />
        </inner>
    </xsl:for-each>
</root>

Upvotes: 1

Related Questions