Search code examples
xmlxslt

XSLT - check if tag has a specific element


I have a problem with converting XML file using XSLT. This is how my XML look like (part of it):

 <articles>
...
    <art Name="Product name" BrandName="Brand Name">
    <groups>
       <group ArticleGroupId="64" Default="0"/>
       <group ArticleGroupId="1259" Default="1"/>
       <group ArticleGroupId="1401" Default="0"/>
    </groups>
    </art>
...
    <art Name="Product name" BrandName="Brand Name">
    <groups>
       <group ArticleGroupId="64" Default="0"/>
       <group ArticleGroupId="1401" Default="0"/>
    </groups>
    </art>
...
</articles>

I want to create file with products that contains ArticleGroupID 1259.

I tried with this code:

<xsl:for-each select="articles/art">
                                
    <xsl:if test="(
    @ArticleGroupId = '1259')"> 
                                        
                <product>
                    <producer>
                        <xsl:attribute name="name">
                        <xsl:value-of select="@BrandName">
                        </xsl:value-of>
                        </xsl:attribute>
                    </producer>
                    <description>
                        <name><xsl:value-of select="@Name"></xsl:value-of></name>
                    </description>
                </product>

     </xsl:if> 
</xsl:for-each>

But it just don't work. I know my xsl:if is wrong, but i don't know how to deal with it. Please, help :)


Solution

  • Your test="@ArticleGroupId = '1259'" is looking for an ArticleGroupId attribute of the art element, and it doesn't have one.

    You want test="groups/group/@ArticleGroupId = '1259'.

    This takes advantage of the fact that in an XPath comparison X = Y where X is a node-set and Y is a literal value, the result will be true if any node in X compares equal to Y.

    Incidentally, you can simplify this:

                <producer>
                    <xsl:attribute name="name">
                    <xsl:value-of select="@BrandName">
                    </xsl:value-of>
                    </xsl:attribute>
                </producer>
    

    to

                <producer name="{@BrandName}"/>