How to use Foreach with xslt in an xml file

Asked

Viewed 110 times

0

I’m having trouble using a file ".xml" and an archive ".xslt"

Follow the code below: listAlunos.xml

<?xml version="1.0" encoding="UTF-8"?>
<listaAlunos>
  <aluno>
    <nome>Bill</nome>
    <sobrenome>Gates</sobrenome>
  </aluno>  
   <aluno>
    <nome>Steve</nome>
    <sobrenome>Jobs</sobrenome>
  </aluno> 
  <aluno>
    <nome>Mark</nome>
    <sobrenome>Zuckerberg</sobrenome>
  </aluno>  
  <aluno>
    <nome>Larry</nome>
    <sobrenome>Page</sobrenome>
  </aluno>
  <aluno>
    <nome>Orkut</nome>
    <sobrenome>Buyukkokten</sobrenome>
  </aluno>

</listaAlunos>

The other file is this: foreach.xslt

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
    <h2>Alunos da Sala</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Nome</th>
        <th>Sobrenome</th>
      </tr>
      <xsl:for-each select="/listaAlunos/aluno">
         <tr>
          <td><xsl:value-of select="nome"/></td>
          <td><xsl:value-of select="sobrenome"/></td>
         </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>

1 answer

0

You can process the XML file using an XSLT processor to generate an HTML (via tool or server) or link using a processing instruction (which will be interpreted by the browser). To make this link, add the line below in the XML file:

<?xml-stylesheet href="foreach.xslt" type="text/xsl"?>

Assuming both are in the same directory and will be uploaded directly by the browser or via a web server that will send the files as text, plain XML or HTML.

The resulting effect will be the HTML below:

<html>
   <body>
      <h2>Alunos da Sala</h2>
      <table border="1">
         <tr bgcolor="#9acd32">
            <th>Nome</th>
            <th>Sobrenome</th>
         </tr>
         <tr>
            <td>Bill</td>
            <td>Gates</td>
         </tr>
         <tr>
            <td>Steve</td>
            <td>Jobs</td>
         </tr>
         <tr>
            <td>Mark</td>
            <td>Zuckerberg</td>
         </tr>
         <tr>
            <td>Larry</td>
            <td>Page</td>
         </tr>
         <tr>
            <td>Orkut</td>
            <td>Buyukkokten</td>
         </tr>
      </table>
   </body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.