Access nested element value in foreach xsl

Advertisements

I use foreach loop <xsl:for-each select="catalog/cd[artist[@id='2']]"> to loop in cd. Then, I want to get title1 tag value <title1>Unchain my heart</title1> using title/title1 But , output nothing.

<?xml version="1.0" encoding="UTF-8"?>
 <catalog>
  <cd>
  <title>Red</title>
  <artist>The Communards</artist>
  <country>UK</country>
  <company>London</company>
  <price>7.80</price>
  <year>1987</year>
 </cd>
 <cd>
  <title>
    <title1>Unchain my heart</title1>
    <title2>Unchain my heart 2</title2>
  </title>
  <artist id='2'>Joe Cocker</artist>
  <country>USA</country>
  <company>EMI</company>
  <price>8.20</price>
  <year>1987</year>
</cd>
</catalog>

format.xsl

<?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
   <xsl:for-each select="catalog/cd[artist[@id='2']]">
     <xsl:value-of select="title/title1"/>
   </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

>Solution :

Your stylesheet uses the (default) xml output method, but its output is not well-formed XML because it doesn’t have a root element; it just produces a document consisting of a single text node Unchain my heart. My guess is that’s what’s causing your problem.

I’ve changed your value-of into a copy-of:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
   <xsl:for-each select="catalog/cd[artist[@id='2']]">
     <xsl:copy-of select="title/title1"/>
   </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

Result:

<?xml version="1.0" encoding="UTF-8"?><title1>Unchain my heart</title1>

Alternatively, if you really do want your output to be a plain text file rather than an XML file, change your output method to text:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:template match="/">
   <xsl:for-each select="catalog/cd[artist[@id='2']]">
     <xsl:value-of select="title/title1"/>
   </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

Result:

Unchain my heart

Leave a ReplyCancel reply