conditional loop in XSLT



I have a sample XML which have to loop 3 times to get output. But sometime, one of the loop (attrQualMany name="pagecontain") can be optional, which is creating problem here.


The sample XML is



<document>
<item>
<ID>1000909090</ID>
<flex>
<attrGroupMany name="pageinfo">
<row>
<attrQualMany name="pageinput">
<value qual="en">User Intake</value>
</attrQualMany>
<attrGroupMany name="pagetype"> <!-- Mandatory Loop -->
<row>
<attr name="pagemeasure">EXACT</attr>
<attrQualMany name="pagecontain"> <!-- Optional Loop -->
<value qual="GR1">20</value>
<value qual="GR2">21</value>
</attrQualMany>
</row>
<row>
<attr name="pagemeasure">EXACT</attr>
<attrQualMany name="pagecontain"><!-- Optional Loop -->
<value qual="JH1">30</value>
<value qual="JH2">31</value>
</attrQualMany>
</row>
</attrGroupMany>
<attr name="pagestate">PREPARED</attr>
<attrQualMany name="pagewidth"> <!-- Mandatory Loop -->
<value qual="OZ">10</value>
<value qual="AB">11</value>
</attrQualMany>
</row>
</attrGroupMany>
</flex>
</item>
</document>


I am using below XSLT which is working fine when we have all the loops present.


XSLT



<xsl:stylesheet xmlns:xsl="http://ift.tt/tCZ8VR" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/document">
<CatalogItem>
<RelationshipData>
<Relationship>
<RelationType>PAGEDETAILSINFO</RelationType>
<xsl:variable name="pagetype" select="//attrGroupMany[@name = 'pagetype']/row"/>
<xsl:variable name="pagecontain" select="$pagetype//attrQualMany[@name='pagecontain']"/>
<xsl:variable name="pagewidth" select="//attrQualMany[@name = 'pagewidth']/value"/>
<RelatedItems count="{count($pagetype) * count($pagecontain) * count($pagewidth)}">
<xsl:for-each select="$pagetype">
<xsl:variable name="attr" select="attr[@name='pagemeasure']"/>
<xsl:for-each select=".//attrQualMany[@name='pagecontain']/value">
<xsl:variable name="value" select="."/>
<xsl:variable name="value1" select="./@qual"/>
<xsl:for-each select="$pagewidth">
<RelatedItem referenceKey="{concat('PAGEDETAILSINFO','-',ancestor::item/ID,'-',../../attr[@name='pagestate'], '-', . ,'-', @qual, '-', $attr , '-',$value, '-', $value1)}"/>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</RelatedItems>
</Relationship>
</RelationshipData>
</CatalogItem>
</xsl:template>
</xsl:stylesheet>


If the XML is not having optional loop and looks like below, it is not returning any value



<document>
<item>
<ID>1000909090</ID>
<flex>
<attrGroupMany name="pageinfo">
<row>
<attrQualMany name="pageinput">
<value qual="en">User Intake</value>
</attrQualMany>
<attrGroupMany name="pagetype">
<row>
<attr name="pagemeasure">EXACT</attr>
</row>
<row>
<attr name="pagemeasure">EXACT</attr>
</row>
</attrGroupMany>
<attr name="pagestate">PREPARED</attr>
<attrQualMany name="pagewidth">
<value qual="OZ">10</value>
<value qual="AB">11</value>
</attrQualMany>
</row>
</attrGroupMany>
</flex>
</item>
</document>

No comments:

Post a Comment