Search code examples
xmlxsltxslt-1.0cyclevalue-of

xslt - select car names of user


I have xml file below:

<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet version="1.0" type="text/xml" href="template.xsl" ?>
<source>
    <man name="John" surname="Piterson" >
        <cars>
            <car name="Lamborgini Gallardo" maxspeed="400km" />
            <car name="Honda" maxspeed="200km" />
        </cars>
        <appartments>
            <appartment city="New York" />
            <appartment city="Tokio" />
        </appartments>
    </man>
</source>

and i have xsl template below, it should display list of cars

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:template match="/" >
        <html>
            <body>
                <h1>Users info</h1>
                <div><strong>The cars of John</strong></div>
                <xsl:for-each select="/man/cars/car" >
                    <div>
                        <xsl:value-of select="car@name" />
                    </div>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

I need to print all car names of John, the <xsl:for-each - not work in that case, how to do that?


Solution

  • <xsl:for-each select="/source/man[@name='John'][@surname='Piterson']/cars/car" >
      <div>
        <xsl:value-of select="@name" />
      </div>
    </xsl:for-each>