Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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}"/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading