Basic Example

기초 예

The basic example will load an XML file and apply a XSL transformation on it. These are the same files used in the Generating HTML example in the XSLT in Netscape Gecko article. The XML file describes an article and the XSL file formats the information for display.

그림4 : XML 파일

XML Document (example1.xml):

  <?xml version="1.0"?>
    <myNS:Title>My Article</myNS:Title>
      <myNS:Author company="Foopy Corp.">Mr. Foo</myNS:Author>
      <myNS:Author>Mr. Bar</myNS:Author>
         The <b>rain</b> in <u>Spain</u> stays mainly in the plains.

그림 5 : XSLT 스타일쉬트

XSL Stylesheet (example1.xsl):

  <?xml version="1.0"?>
  <xsl:stylesheet version="1.0"

    <xsl:output method="html" />

    <xsl:template match="/">


            <xsl:value-of select="/myNS:Article/myNS:Title"/>

          <style type="text/css">
            .myBox {margin:10px 155px 0 50px; border: 1px dotted #639ACE; padding:0 5px 0 5px;}


          <p class="myBox">
            <span class="title">
              <xsl:value-of select="/myNS:Article/myNS:Title"/>
            </span> </br>

            Authors:   <br />
              <xsl:apply-templates select="/myNS:Article/myNS:Authors/myNS:Author"/>

          <p class="myBox">
            <xsl:apply-templates select="//myNS:Body"/>



    <xsl:template match="myNS:Author">
       --   <xsl:value-of select="." />

      <xsl:if test="@company">
       ::   <b>  <xsl:value-of select="@company" />  </b>

      <br />

    <xsl:template match="myNS:Body">
        <xsl:apply-templates select="@*|node()"/>

    <xsl:template match="@*|node()">
          <xsl:apply-templates select="@*|node()"/>

The example loads using synchronous XMLHTTPRequest both the .xsl (xslStylesheet) and the .xml (xmlDoc) files into memory. The .xsl file is then imported (xsltProcessor.importStylesheet(xslStylesheet)) and the transformation run (xsltProcessor.transformToFragment(xmlDoc, document)). This allows fetching of data after the page has been loaded, without initiating a fresh page load.

그림 6 : 예view example

var xslStylesheet;
var xsltProcessor = new XSLTProcessor();
var myDOM;

var xmlDoc;

function Init(){

  // load the xslt file, example1.xsl
  var myXMLHTTPRequest = new XMLHttpRequest();"GET", "example1.xsl", false);

  xslStylesheet = myXMLHTTPRequest.responseXML;

  // load the xml file, example1.xml
  myXMLHTTPRequest = new XMLHttpRequest();"GET", "example1.xml", false);

  xmlDoc = myXMLHTTPRequest.responseXML;

  var fragment = xsltProcessor.transformToFragment(xmlDoc, document);

  document.getElementById("example").innerHTML = "";

  myDOM = fragment;