Azygous92
Azygous92

Reputation: 1

XML output generating using XSLT

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>

Upvotes: 0

Views: 33

Answers (2)

imran
imran

Reputation: 461

<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>

Upvotes: 0

zx485
zx485

Reputation: 29022

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']" />  

Upvotes: 1

Related Questions