简体   繁体   中英

XSLT transformation for an xml that has nodes with the same name

I have an XML in this format,

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd>
    <title>Empire Burlesque</title>
    <title>Hide your heart</title>
    <title>Greatest Hits</title>
    <title>Still got the blues</title>
    <title>Eros</title>
    <title>One night only</title>
</cd>
</catalog>

The XSLT for this XML is,

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
      <body>
        <table border="1">
          <tr>
            <th>Title</th>
          </tr>
          <xsl:for-each select="catalog/cd/title">
          <tr>
            <td><xsl:value-of select="title"/></td>
          </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
</xsl:template>
</xsl:stylesheet>

I want the output to look like,

Title

Empire Burlesque
Hide your heart
Greatest Hits
Still got the blues
Eros
One night only

When i try to transform the above XML, i am getting an empty table, but with no titles in it. Please help me with this so i can get the expected output as shown above. Thanks in advance.

There is just a minor flaw in your solution. See my comment in the following code:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
      <body>
        <table border="1">
          <tr>
            <th>Title</th>
          </tr>
          <xsl:for-each select="catalog/cd/title">
          <tr>
            <!-- you have to reference '.' instead of 'title' because this is the
              current context node since you iterate over 'title' elements with
              for-each -->
            <td><xsl:value-of select="."/></td>
          </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
</xsl:template>
</xsl:stylesheet>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM