sexta-feira, abril 13, 2007

Conteúdo XML formatado com XSL e JavaScript - CROSSBROWSER!

Dae pessoal.
Vou postar aqui uma maneira crossbrowser de renderizar conteúdo de arquivos XML formatados com XSL usando JavaScript.

Criando o arquivo contatos.xml:


<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="contatos.xsl"?>
<catalogo>
  <contato>
    <codigo>1</codigo>
    <nome>John Due</nome>
    <dddresidencial>51</dddresidencial>
    <foneresidencial>5555-6666</foneresidencial>
    <dddcomercial>51</dddcomercial>
    <fonecomercial>4444-5555</fonecomercial>
    <dddcelular>51</dddcelular>
    <fonecelular>8888-9999</fonecelular>
    <e_mail>jdue@jdue.net</e_mail>
  </contato>
  <contato>
    <codigo>2</codigo>
    <nome>Fulano de Tal</nome>
    <dddresidencial>51</dddresidencial>
    <foneresidencial>3333-4444</foneresidencial>
    <dddcomercial>51</dddcomercial>
    <fonecomercial>2222-3333</fonecomercial>
    <dddcelular>51</dddcelular>
    <fonecelular>9999-8888</fonecelular>
    <e_mail>fulano_tal@terra.com.br</e_mail>
  </contato>
  <contato>
    <codigo>3</codigo>
    <nome>Marta Kent</nome>
    <dddresidencial>51</dddresidencial>
    <foneresidencial>3333-2222</foneresidencial>
    <dddcomercial>51</dddcomercial>
    <fonecomercial>2222-1111</fonecomercial>
    <dddcelular>51</dddcelular>
    <fonecelular>8888-7777</fonecelular>
    <e_mail>martak@yahoo.com.br</e_mail>
  </contato>
</catalogo>


Criando o arquivo contatos.xsl:


<?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>
      <head>
        <style>
          * {
            font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
            color: #2988EA;
          }

          table.listResult {
            border-top: 1px solid #54A6FC;
            border-bottom: 1px solid #54A6FC;
            padding: 0px 0px 0px 0px;
          }

          tr.head {
            background-color: #CCE5FF;
          }

          tr.linhaImpar {
            background-color: #E3F1FF;
          }

          h2 {
            font-size: 10pt;
          }

          td, th {
            font-size: 8pt;

          }
        </style>
      </head>
      <body>
        <h2>Catálogo de Endereços</h2>
        <table border="0" cellpadding="7" cellspacing="0" class='listResult'>
          <tr class='head'>
            <th align="left">Cód.</th>
            <th align="left">Nome</th>
            <th align="left">Fone Residencial</th>
            <th align="left">Fone Comercial</th>
            <th align="left">Fone Celular</th>
            <th align="left">E-mail</th>
          </tr>
          <xsl:for-each select="catalogo/contato">
            <xsl:sort select="nome"/>
              <tr>
                <xsl:choose>
                 <xsl:when test="position() mod 2 = 0">
                    <xsl:attribute name="class">linhaPar</xsl:attribute>
                 </xsl:when>
                 <xsl:otherwise>
                    <xsl:attribute name="class">linhaImpar</xsl:attribute>
                 </xsl:otherwise>
                </xsl:choose>
                <td><xsl:value-of select="codigo" /></td>
                <td><xsl:value-of select="nome" /></td>
                <td>(<xsl:value-of select="dddresidencial" />) <xsl:value-of select="foneresidencial" /></td>
                <td>(<xsl:value-of select="dddcomercial" />) <xsl:value-of select="fonecomercial" /></td>
                <td>(<xsl:value-of select="dddcelular" />) <xsl:value-of select="fonecelular" /></td>
                <td><xsl:value-of select="e_mail" /></td>
              </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>


Criando o arquivo contatos.html:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt">
  <head>
    <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=ISO-8859-1"/>
    <meta http-equiv="pragma" content="no-cache"/>
    <meta name="author" content="Jean Jorge Michel"/>
    <meta name="robots" content="ALL"/>
    <meta name="revisit-after" content="4"/>
    <meta name="MSSmartTagsPreventParsing" content="true"/>
    <meta name="distribution" content="Global" />
    <meta name="rating" content="General"/>
    <meta name="language" content="pt-br"/>
    <meta name="description" content="Exemplo de uso de XML com XSL sendo aplicados em páginas HTML com JavaScript" />
    <meta name="keywords" content="xml, xsl, parser xml, crossbrowser, javascript"/>
    <title>.Jean J. Michel.</title>
  </head>
  <body id="conteudo">
    <script>
      var xml;
      var xsl;
      var processador;
      var xmlRetorno;
      var xslt;
      var conteudo;
      var localRetorno = document.getElementById('conteudo');

      if (window.ActiveXObject) { //Para IE

        xml = new ActiveXObject("Microsoft.XMLDOM");
        xml.async = false;
        xml.load("contatos.xml");

        xsl = new ActiveXObject("Microsoft.XMLDOM");
        xsl.async = false;
        xsl.load("contatos.xsl");

        document.write(xml.transformNode(xsl));
      }
      else if (document.implementation &&
               document.implementation.createDocument) { //Para FF, Mozilla, etc...

        processador = new XSLTProcessor();

        xls = new XMLHttpRequest();
        xls.open("POST", "contatos.xsl", false);
        xls.send(null);

        xslt = xls.responseXML;
        processador.importStylesheet(xslt);

        xml = new XMLHttpRequest();
        xml.open("POST", "contatos.xml", false);
        xml.send(null);

        xmlRetorno = xml.responseXML;

        conteudo = processador.transformToFragment(xmlRetorno, document);
        localRetorno.innerHTML = '';
        localRetorno.appendChild(conteudo);
      }
      else {
        alert("Browser desconhecido ou desatualizado!");
      }
    </script>
    <small>Acesse <a href="http://www.jeanjmichel.blogspot.com">jeanjmichel.blogspot.com</a> para mais exemplos.</small>
  </body>
</html>

O resultado:

Imagem do exemplo

Voce pode acessar o conteúdo aqui:

http://br.geocities.com/sadbuttruebr/blog/
scripts_posts/contatos.html


http://br.geocities.com/sadbuttruebr/blog/
scripts_posts/contatos.xml


http://br.geocities.com/sadbuttruebr/blog/
scripts_posts/contatos.xsl

Um comentário:

Kleber Soares disse...

Otima materia Jean!
Me ajudou bastante!
obrigado e parabens pelo blog!
espero q continue no ar por mto tempo!
abraco