0

I have an XML source file as an input which is the following:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <car>
    <brand>Mercedes</brand>
    <type>ClassA</type>
    <engine>Diesel</engine>
    <seats>5</seats>    
  </car>

  <car>
    <brand>Audi</brand>
    <type>A8</type>
    <engine>Diesel</engine>
    <seats>2</seats>    
  </car>

  <car>
    <brand>Mercedes</brand>
    <type>ClassB</type>
    <engine>Petrol</engine>
    <seats>5</seats>
  </car>
</catalog>

I need to filter the cars using an .xsl styleshett (XSLT) according to various data (for example: I want the list of the Mercedes brand cars with all of it's properties). My output file's structure (XML tags) has to be the same as the input after the filter.

In this case (filter Mercedes brand cars) the output has to be:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <car>
     <brand>Mercedes</brand>
     <type>ClassA</type>
     <engine>Diesel</engine>
     <seats>5</seats>    
  </car>

  <car>
    <brand>Mercedes</brand>
    <type>ClassB</type>
    <engine>Petrol</engine>
    <seats>5</seats>
  </car>
</catalog>

2 Answers 2

1

You can simply filter out any non-Mercedes brand cars with

<xsl:template match="car[brand!='Mercedes']" /> 

Combine this with the identity template to copy all remaining nodes:

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

You can reverse the approach by explicitly excluding certain brands (here 'Audi' and 'Ford') and keeping all the others with

<xsl:template match="car[brand='Audi' or brand='Ford']" />  
Sign up to request clarification or add additional context in comments.

1 Comment

+1 It's also good to note that car[brand!='Mercedes'] only filters out cars that have a brand element. To also filter out cars that don't have a brand element use car[not(brand='Mercedes')] instead. Also, if using XSLT 2.0+, you can write car[brand='Audi' or brand='Ford'] as car[brand=('Audi','Ford')].
0
<xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>


    <xsl:template match="catalog">
        <xsl:element name="catalog">
            <xsl:for-each select="//car">
                <xsl:choose>
                    <xsl:when test=".[brand='Audi']"/>
                    <xsl:otherwise>
                        <xsl:copy-of select="."/>
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each>
        </xsl:element>
    </xsl:template>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.