简体   繁体   中英

<xsl:apply-templates> usage with <xsl:for-each> using XSLT1.0 transformations

I am new to XSLT and I am struggling with this one. I have a xml like this:

<rowset>
<row num="l">
<empno>7839</empno>
<ename>KING</ename>
<country>Australia</country>
</row>
<row num="2">
<empno>7788</empno>
<ename>REIJK/ename>
<country>Japan</country>
</row>
</rowset>

I need to tranform using XSLT into the below format in HTML:

<hl>Names</hl>
<ul>
<li>KING</li>
<li>REIJK/li>
</ul>
<hl>Countries</hl>
<ul>
<li>Australia</li>
<li>Japan</li>
</ul>

I have the below code.I using for-each unable to get the tags.Please would be really appreciated.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<h1>Names</h1>
<ul>
<li>
<xsl:for-each select="/row/ename">
<xsl:apply-templates select="rowset/row/ename"/>
</xsl:for-each>
</li>
</ul>
<h1>Countries</h1>
<ul>
<li>
<xsl:apply-templates select="rowset/row/country"/>
</li>
</ul>
</xsl:template>
<xsl:template match="/row/ename">
<xsl:value-of select="ename"/>
</xsl:template>
<xsl:template match="/row/country">
<xsl:for-each select="country">
<li>
<xsl:value-of select="country"/>
</li>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

The output for the code I got is below:

<h1>Names</h1>
<ul>
<li/>
</ul>
<h1>Countries</h1>
<ul>
<li>AustraliaJapan</li>
</ul>

You're missing rowset from your XPaths where you need it and using it where you don't need it.

You can do this cleanly without for-each . If you want to repeat <li> for each name or country, then <li> would need to be inside the for-each or template .

When the following is applied to your sample input (with the missing < added)

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <h1>Names</h1>
    <ul>
      <xsl:apply-templates select="rowset/row/ename"/>
    </ul>
    <h1>Countries</h1>
    <ul>
      <xsl:apply-templates select="rowset/row/country"/>
    </ul>
  </xsl:template>

  <xsl:template match="ename | country">
    <li>
      <xsl:value-of select ="."/>
    </li>
  </xsl:template>
</xsl:stylesheet>

The result is:

<h1>Names</h1>
<ul>
  <li>KING</li>
  <li>REIJK</li>
</ul>
<h1>Countries</h1>
<ul>
  <li>Australia</li>
  <li>Japan</li>
</ul>

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