0

I am completely new in XSLT. So I am trying to make an example that is supposed to output the value of an element. The output format is plain text format. This is the XML file called cdcatalog.xml:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="catalog.xsl"?>
<catalog>
    <cd>
        <title>Empire</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>
            <europe_country>Bulgaria</europe_country>
            <azia_coutry>China</azia_coutry>
        </country>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
    </cd>
</catalog>

And this is the XSL file called cdcatalog.xsl

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text"/>
    <xsl:template match="/">
        <xsl:for-each select="cd">
            <xsl:value-of select="title"/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

The output I expect is something like this

Empire
Hide your heart

But nothing appears in the output window. Where am I wrong? Thank you in advance.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Radoslaw Krasimirow
  • 1,833
  • 2
  • 18
  • 28

2 Answers2

2
Community
  • 1
  • 1
Matt Gibson
  • 37,886
  • 9
  • 99
  • 128
1

When writing templates, try to target (i.e. match) directly the content you are interested in (the title elements, in this case).

XSLT Stylesheet

As you can see, there is a second template that matches text(). If we omit it, all text content from the input document is output, because that is the default behaviour of the XSLT processor for text nodes.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text" encoding="UTF-8" />

    <xsl:template match="title">
      <xsl:value-of select="."/>
      <xsl:text>&#10;</xsl:text>
    </xsl:template>

    <xsl:template match="text()"/>

</xsl:transform>

Text Output

Empire
Hide your heart

Try this solution online here.


By the way, make sure your elements are consistently named. An element called azia_coutry is completely different from asia_coutry or asia_country.

Mathias Müller
  • 22,203
  • 13
  • 58
  • 75