Home > Blockchain >  If condition inside a for-each loop returns all results multiplied - XSLT
If condition inside a for-each loop returns all results multiplied - XSLT

Time:07-21

This is a part of my XML:

<record>
    <leader>01707nkm a2200421 i 4500</leader>
    <controlfield tag="001">9925375136006986</controlfield>
    <controlfield tag="003">CZ-PrCU</controlfield>
    <controlfield tag="005">20220502141021.0</controlfield>
    <controlfield tag="006">m     o  c        </controlfield>
    <controlfield tag="007">gs#cd##z#</controlfield>
    <controlfield tag="007">cc#cd##z#</controlfield>
    <controlfield tag="008">220128q19uu1945xx nnn            s|zxx d</controlfield>
</record>

And this is my XSLT template:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output encoding="UTF-8" indent="yes" method="xml"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:template match="/">
       <xsl:for-each select="/record/controlfield[@tag=007]">
                
                <xsl:if test="/record/controlfield[@tag=007][substring(text(),1,1)='g'][substring(text(),2,1)='s']">
                    <form authority="marccategory">electronic resource</form>
                </xsl:if>
                
                <xsl:if test="/record/controlfield[@tag=007][substring(text(),1,1)='c'][substring(text(),2,1)='c']">
                    <form authority="marccategory">slide</form>    
                </xsl:if>
                
    
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Result I get is:

<?xml version="1.0" encoding="UTF-8"?>
<form authority="marccategory">electronic resource</form>
<form authority="marccategory">slide</form>
<form authority="marccategory">electronic resource</form>
<form authority="marccategory">slide</form>

Can you help me to uderstand what am I doing wrong? Problem is that I got duplicated results. The condition should be True just in a particular field - not in both field 007.

You can see it here: http://xsltransform.net/gVhDDyG/2

The desired result which I would expect to achive by this code is:

<?xml version="1.0" encoding="UTF-8"?>
<form authority="marccategory">electronic resource</form>
<form authority="marccategory">slide</form>

CodePudding user response:

The instruction:

<xsl:for-each select="/record/controlfield[@tag=007]">

puts you in the context of controlfield. From this context, the test of the current value should use a relative path, not an absolute one as your attempt does - e.g.

<xsl:if test="substring(text(),1,1)='g' and substring(text(),2,1)='s'">

which I believe could be simplified to:

<xsl:if test="starts-with(., 'gs')">

I would also suggest using xsl:choose for mutually exclusive options instead of multiple xsl:if instructions.

  • Related